lib/editor/tiny/plugins/aiplacement/amd/src/mediaimage.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * AI Modal for Tiny.
  17. *
  18. * @module tiny_aiplacement/mediaimage
  19. * @copyright 2024 Matt Porritt <matt.porritt@moodle.com>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import {getString} from 'core/str';
  23. import MediaImage from 'tiny_media/image';
  24. import Notification from 'core/notification';
  25. import {prefetchStrings} from 'core/prefetch';
  26. prefetchStrings('core_ai', [
  27. 'contentwatermark',
  28. ]);
  29. export default class AiMediaImage extends MediaImage {
  30. constructor(editor, url, alt) {
  31. super(editor); // Call the parent class constructor
  32. this.generatedImageUrl = url;
  33. this.altText = alt;
  34. getString('contentwatermark', 'core_ai').then((watermark) => {
  35. this.watermark = watermark;
  36. return;
  37. }).catch(Notification.exception);
  38. }
  39. getSelectedImage() {
  40. const imgElement = document.createElement('img');
  41. // Set attributes for the img element
  42. imgElement.src = this.generatedImageUrl;
  43. imgElement.alt = this.truncateAltText(this.altText);
  44. return imgElement;
  45. }
  46. /**
  47. * Truncate the alt text if it is longer than the maximum length.
  48. * @param {String} altText The alt text
  49. * @return {string} The truncated alt text
  50. */
  51. truncateAltText(altText) {
  52. const maximumAltTextLength = 125;
  53. const watermark = ' - ' + this.watermark;
  54. const ellipsis = '...';
  55. // Append the watermark to the alt text.
  56. if (altText.length + watermark.length <= maximumAltTextLength) {
  57. altText = altText + watermark;
  58. } else {
  59. const remainingLength = maximumAltTextLength - watermark.length - ellipsis.length;
  60. altText = altText.substring(0, remainingLength) + ellipsis + watermark;
  61. }
  62. return altText;
  63. }
  64. }