widget.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. IKernel
  5. } from 'jupyter-js-services';
  6. import {
  7. Message
  8. } from 'phosphor-messaging';
  9. import {
  10. Widget
  11. } from 'phosphor-widget';
  12. import {
  13. ABCWidgetFactory, IDocumentModel, IWidgetFactory, IDocumentContext
  14. } from '../docregistry';
  15. /**
  16. * A widget for images.
  17. */
  18. export
  19. class ImageWidget extends Widget {
  20. /**
  21. * Create the node for the image widget.
  22. */
  23. static createNode(): HTMLElement {
  24. return document.createElement('img');
  25. }
  26. /**
  27. * Construct a new image widget.
  28. */
  29. constructor(context: IDocumentContext<IDocumentModel>) {
  30. super();
  31. this._context = context;
  32. this.node.tabIndex = -1;
  33. this.node.style.overflowX = 'auto';
  34. this.node.style.overflowY = 'auto';
  35. if (context.model.toString()) {
  36. this.update();
  37. }
  38. context.pathChanged.connect(() => {
  39. this.update();
  40. });
  41. context.model.contentChanged.connect(() => {
  42. this.update();
  43. });
  44. }
  45. /**
  46. * Dispose of the resources used by the widget.
  47. */
  48. dispose(): void {
  49. if (this.isDisposed) {
  50. return;
  51. }
  52. this._context = null;
  53. super.dispose();
  54. }
  55. /**
  56. * Handle `update-request` messages for the widget.
  57. */
  58. protected onUpdateRequest(msg: Message): void {
  59. this.title.text = this._context.path.split('/').pop();
  60. let node = this.node as HTMLImageElement;
  61. let content = this._context.model.toString();
  62. let cm = this._context.contentsModel;
  63. node.src = `data:${cm.mimetype};${cm.format},${content}`;
  64. }
  65. private _context: IDocumentContext<IDocumentModel>;
  66. }
  67. /**
  68. * A widget factory for images.
  69. */
  70. export
  71. class ImageWidgetFactory extends ABCWidgetFactory implements IWidgetFactory<ImageWidget, IDocumentModel> {
  72. /**
  73. * Create a new widget given a context.
  74. */
  75. createNew(context: IDocumentContext<IDocumentModel>, kernel?: IKernel.IModel): ImageWidget {
  76. return new ImageWidget(context);
  77. }
  78. }