ImageChooserWidget.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { Chooser, ChooserFactory } from '.';
  2. export class ImageChooser extends Chooser {
  3. // eslint-disable-next-line no-undef
  4. chooserModalClass = ImageChooserModal;
  5. initHTMLElements(id) {
  6. super.initHTMLElements(id);
  7. this.previewImage = this.chooserElement.querySelector(
  8. '[data-chooser-image]',
  9. );
  10. }
  11. /**
  12. * Constructs the initial state of the chooser from the rendered (static) HTML.
  13. * The state is either null (no image chosen) or an object containing the image details.
  14. *
  15. * @returns {Object|null} The initial state of the chooser. If an image is chosen,
  16. * the state object contains the following properties:
  17. * - id: {number} The ID of the chosen image.
  18. * - edit_url: {string} The URL to edit the chosen image.
  19. * - title: {string} The title of the chosen image.
  20. * - preview: {Object} An object containing the preview details of the chosen image:
  21. * - url: {string} The URL of the preview image.
  22. * - width: {string} The width of the preview image.
  23. * - height: {string} The height of the preview image.
  24. */
  25. getStateFromHTML() {
  26. const state = super.getStateFromHTML();
  27. if (state) {
  28. state.preview = {
  29. url: this.previewImage.getAttribute('src'),
  30. width: this.previewImage.getAttribute('width'),
  31. height: this.previewImage.getAttribute('height'),
  32. };
  33. }
  34. return state;
  35. }
  36. renderState(newState) {
  37. super.renderState(newState);
  38. this.previewImage.setAttribute('src', newState.preview.url);
  39. this.previewImage.setAttribute('width', newState.preview.width);
  40. }
  41. }
  42. export class ImageChooserFactory extends ChooserFactory {
  43. widgetClass = ImageChooser;
  44. // eslint-disable-next-line no-undef
  45. chooserModalClass = ImageChooserModal;
  46. }