index.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. IIterable, IterableOrArrayLike
  5. } from 'phosphor/lib/algorithm/iteration';
  6. import {
  7. JSONObject
  8. } from 'phosphor/lib/algorithm/json';
  9. import {
  10. find
  11. } from 'phosphor/lib/algorithm/searching';
  12. import {
  13. Vector
  14. } from 'phosphor/lib/collections/vector';
  15. import {
  16. Token
  17. } from 'phosphor/lib/core/token';
  18. import {
  19. Widget
  20. } from 'phosphor/lib/ui/widget';
  21. import {
  22. ISanitizer
  23. } from '../common/sanitizer';
  24. import {
  25. ICommandLinker
  26. } from '../commandlinker';
  27. import {
  28. HTMLRenderer, LatexRenderer, ImageRenderer, TextRenderer,
  29. JavascriptRenderer, SVGRenderer, MarkdownRenderer, PDFRenderer
  30. } from '../renderers';
  31. /* tslint:disable */
  32. /**
  33. * The rendermime token.
  34. */
  35. export
  36. const IRenderMime = new Token<IRenderMime>('jupyter.services.rendermime');
  37. /* tslint:enable */
  38. /**
  39. * The rendermime interface.
  40. */
  41. export
  42. interface IRenderMime extends RenderMime {}
  43. /**
  44. * A composite renderer.
  45. *
  46. * #### Notes
  47. * When rendering a mimebundle, a mimetype is selected from the mimetypes by
  48. * searching through the `this.order` list. The first mimetype found in the
  49. * bundle determines the renderer that will be used.
  50. *
  51. * You can add a renderer by adding it to the `renderers` object and
  52. * registering the mimetype in the `order` array.
  53. *
  54. * Untrusted bundles are handled differently from trusted ones. Untrusted
  55. * bundles will only render outputs that can be rendered "safely"
  56. * (see [[RenderMime.IRenderer.isSafe]]) or can be "sanitized"
  57. * (see [[RenderMime.IRenderer.isSanitizable]]).
  58. */
  59. export
  60. class RenderMime {
  61. /**
  62. * Construct a renderer.
  63. */
  64. constructor(options: RenderMime.IOptions) {
  65. for (let mime in options.renderers) {
  66. this._renderers[mime] = options.renderers[mime];
  67. }
  68. this._order = new Vector(options.order);
  69. this._sanitizer = options.sanitizer;
  70. this._resolver = options.resolver || null;
  71. this._linker = options.commandLinker || null;
  72. }
  73. /**
  74. * The object used to resolve relative urls for the rendermime instance.
  75. */
  76. get resolver(): RenderMime.IResolver {
  77. return this._resolver;
  78. }
  79. set resolver(value: RenderMime.IResolver) {
  80. this._resolver = value;
  81. }
  82. /**
  83. * Get an iterator over the ordered list of mimetypes.
  84. *
  85. * #### Notes
  86. * These mimetypes are searched from beginning to end, and the first matching
  87. * mimetype is used.
  88. */
  89. mimetypes(): IIterable<string> {
  90. return this._order.iter();
  91. }
  92. /**
  93. * Render a mimebundle.
  94. *
  95. * @param bundle - the mimebundle to render.
  96. *
  97. * @param trusted - whether the bundle is trusted.
  98. *
  99. * #### Notes
  100. * We select the preferred mimetype in bundle based on whether the output is
  101. * trusted (see [[preferredMimetype]]), and then pass a sanitizer to the
  102. * renderer if the output should be sanitized.
  103. */
  104. render(options: RenderMime.IRenderOptions<string | JSONObject>): Widget {
  105. let { trusted, bundle, injector } = options;
  106. let mimetype = this.preferredMimetype(bundle, trusted);
  107. if (!mimetype) {
  108. return void 0;
  109. }
  110. let rendererOptions = {
  111. mimetype,
  112. source: bundle[mimetype],
  113. injector,
  114. resolver: this._resolver,
  115. sanitizer: trusted ? null : this._sanitizer,
  116. commandLinker: this._linker
  117. };
  118. return this._renderers[mimetype].render(rendererOptions);
  119. }
  120. /**
  121. * Find the preferred mimetype in a mimebundle.
  122. *
  123. * @param bundle - the mimebundle giving available mimetype content.
  124. *
  125. * @param trusted - whether the bundle is trusted.
  126. *
  127. * #### Notes
  128. * For untrusted bundles, only select mimetypes that can be rendered
  129. * "safely" (see [[RenderMime.IRenderer.isSafe]]) or can be "sanitized"
  130. * (see [[RenderMime.IRenderer.isSanitizable]]).
  131. */
  132. preferredMimetype(bundle: RenderMime.MimeMap<string | JSONObject>, trusted=false): string {
  133. return find(this._order, m => {
  134. if (m in bundle) {
  135. let renderer = this._renderers[m];
  136. if (trusted || renderer.isSafe(m) || renderer.isSanitizable(m)) {
  137. return true;
  138. }
  139. }
  140. });
  141. }
  142. /**
  143. * Clone the rendermime instance with shallow copies of data.
  144. */
  145. clone(): IRenderMime {
  146. return new RenderMime({
  147. renderers: this._renderers,
  148. order: this._order.iter(),
  149. sanitizer: this._sanitizer,
  150. commandLinker: this._linker
  151. });
  152. }
  153. /**
  154. * Add a renderer by mimetype.
  155. *
  156. * @param mimetype - The mimetype of the renderer.
  157. * @param renderer - The renderer instance.
  158. * @param index - The optional order index.
  159. *
  160. * ####Notes
  161. * Negative indices count from the end, so -1 refers to the penultimate index.
  162. * Use the index of `.order.length` to add to the end of the render precedence list,
  163. * which would make the new renderer the last choice.
  164. */
  165. addRenderer(mimetype: string, renderer: RenderMime.IRenderer, index = 0): void {
  166. this._renderers[mimetype] = renderer;
  167. this._order.insert(index, mimetype);
  168. }
  169. /**
  170. * Remove a renderer by mimetype.
  171. *
  172. * @param mimetype - The mimetype of the renderer.
  173. */
  174. removeRenderer(mimetype: string): void {
  175. delete this._renderers[mimetype];
  176. this._order.remove(mimetype);
  177. }
  178. /**
  179. * Get a renderer by mimetype.
  180. *
  181. * @param mimetype - The mimetype of the renderer.
  182. *
  183. * @returns The renderer for the given mimetype, or undefined if the mimetype is unknown.
  184. */
  185. getRenderer(mimetype: string): RenderMime.IRenderer {
  186. return this._renderers[mimetype];
  187. }
  188. private _renderers: RenderMime.MimeMap<RenderMime.IRenderer> = Object.create(null);
  189. private _order: Vector<string>;
  190. private _sanitizer: ISanitizer = null;
  191. private _resolver: RenderMime.IResolver;
  192. private _linker: ICommandLinker;
  193. }
  194. /**
  195. * The namespace for RenderMime statics.
  196. */
  197. export
  198. namespace RenderMime {
  199. /**
  200. * The options used to initialize a rendermime instance.
  201. */
  202. export
  203. interface IOptions {
  204. /**
  205. * A map of mimetypes to renderers.
  206. */
  207. renderers: MimeMap<IRenderer>;
  208. /**
  209. * A list of mimetypes in order of precedence (earliest has precedence).
  210. */
  211. order: IterableOrArrayLike<string>;
  212. /**
  213. * The sanitizer used to sanitize html inputs.
  214. */
  215. sanitizer: ISanitizer;
  216. /**
  217. * The initial resolver object.
  218. *
  219. * The default is `null`.
  220. */
  221. resolver?: IResolver;
  222. /**
  223. * The optional command linker object.
  224. */
  225. commandLinker?: ICommandLinker;
  226. }
  227. /**
  228. * Valid rendered object type.
  229. */
  230. export
  231. type RenderedObject = HTMLElement | Widget;
  232. /**
  233. * A map of mimetypes to types.
  234. */
  235. export
  236. type MimeMap<T> = { [mimetype: string]: T };
  237. /**
  238. * Default renderer order
  239. */
  240. export
  241. function defaultRenderers(): IRenderer[] {
  242. return [
  243. new JavascriptRenderer(),
  244. new HTMLRenderer(),
  245. new MarkdownRenderer(),
  246. new LatexRenderer(),
  247. new SVGRenderer(),
  248. new ImageRenderer(),
  249. new PDFRenderer(),
  250. new TextRenderer()
  251. ];
  252. }
  253. /**
  254. * The interface for a renderer.
  255. */
  256. export
  257. interface IRenderer {
  258. /**
  259. * The mimetypes this renderer accepts.
  260. */
  261. readonly mimetypes: string[];
  262. /**
  263. * Whether the input is safe without sanitization.
  264. *
  265. * #### Notes
  266. * A `safe` output is one that cannot pose a security threat
  267. * when added to the DOM, for example when text is added with
  268. * `.textContent`.
  269. */
  270. isSafe(mimetype: string): boolean;
  271. /**
  272. * Whether the input can safely sanitized for a given mimetype.
  273. *
  274. * #### Notes
  275. * A `sanitizable` output is one that could pose a security threat
  276. * if not properly sanitized, but can be passed through an html sanitizer
  277. * to render it safe. These are typically added to the DOM using
  278. * `.innerHTML` or equivalent.
  279. */
  280. isSanitizable(mimetype: string): boolean;
  281. /**
  282. * Render the transformed mime bundle.
  283. *
  284. * @param options - The options used for rendering.
  285. */
  286. render(options: IRendererOptions<string | JSONObject>): Widget;
  287. }
  288. /**
  289. * The options used to render a mime map.
  290. */
  291. export
  292. interface IRenderOptions<T extends string | JSONObject> {
  293. /**
  294. * The mime bundle to render.
  295. */
  296. bundle: MimeMap<T>;
  297. /**
  298. * A callback that can be used to add a mimetype to the original bundle.
  299. */
  300. injector?: (mimetype: string, value: string | JSONObject) => void;
  301. /**
  302. * Whether the mime bundle is trusted (the default is False).
  303. */
  304. trusted?: boolean;
  305. }
  306. /**
  307. * The options used to transform or render mime data.
  308. */
  309. export
  310. interface IRendererOptions<T extends string | JSONObject> {
  311. /**
  312. * The mimetype.
  313. */
  314. mimetype: string;
  315. /**
  316. * The source data.
  317. */
  318. source: T;
  319. /**
  320. * A callback that can be used to add a mimetype to the original bundle.
  321. */
  322. injector?: (mimetype: string, value: string | JSONObject) => void;
  323. /**
  324. * An optional url resolver.
  325. */
  326. resolver?: IResolver;
  327. /**
  328. * An optional html sanitizer.
  329. *
  330. * If given, should be used to sanitize raw html.
  331. */
  332. sanitizer?: ISanitizer;
  333. /**
  334. * An optional command linker.
  335. */
  336. commandLinker: ICommandLinker;
  337. }
  338. /**
  339. * An object that resolves relative URLs.
  340. */
  341. export
  342. interface IResolver {
  343. /**
  344. * Resolve a url to a correct server path.
  345. *
  346. * @param url - The source url.
  347. *
  348. * @param local - Whether to to return the local path versus
  349. * a download path.
  350. *
  351. * @returns a promise which resolves with the resolved url.
  352. */
  353. resolveUrl(url: string, local: boolean): Promise<string>;
  354. }
  355. }