image-insert.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. function insertHtmlAtCursor(textarea, html) {
  2. const start = textarea.selectionStart;
  3. const end = textarea.selectionEnd;
  4. const before = textarea.value.substring(0, start);
  5. const after = textarea.value.substring(end);
  6. textarea.value = before + html + after;
  7. // move cursor after inserted block
  8. textarea.selectionStart = textarea.selectionEnd = start + html.length;
  9. }
  10. function insertSelectedImage() {
  11. const select = document.getElementById("imageSelect");
  12. const imageId = select.value;
  13. if (!imageId) {
  14. alert("Please select media first.");
  15. return;
  16. }
  17. const mediaType = select.selectedOptions[0].dataset.mediaType;
  18. const src = `/api/v1/images/${encodeURIComponent(imageId)}`;
  19. const media = mediaType === "video/webm"
  20. ? `<video src="${src}" class="rounded img-fluid" controls preload="metadata"></video>`
  21. : `<img src="${src}" class="rounded img-fluid" alt="">`;
  22. const html = `<div class="text-center">
  23. ${media}
  24. </div>`;
  25. const textarea = document.getElementById("myTextarea");
  26. insertHtmlAtCursor(textarea, html);
  27. }
  28. function toggleDropdown(el) {
  29. const options = el.parentElement.querySelector('.options');
  30. const open = options.style.display === "block";
  31. document.querySelectorAll('.image-select .options').forEach(o => o.style.display = "none");
  32. options.style.display = open ? "none" : "block";
  33. }
  34. function chooseImage(optionEl) {
  35. const id = optionEl.dataset.id;
  36. const container = optionEl.closest('.image-select');
  37. // set visible label
  38. container.querySelector('.selected span').textContent = id;
  39. // set real select value
  40. container.querySelector('.real-select').value = id;
  41. // close dropdown
  42. container.querySelector('.options').style.display = "none";
  43. }
  44. // close dropdown when clicking outside
  45. document.addEventListener("click", function (e) {
  46. if (!e.target.closest(".image-select")) {
  47. document.querySelectorAll('.image-select .options').forEach(o => o.style.display = "none");
  48. }
  49. });
  50. function showPreview(src) {
  51. const box = document.getElementById('previewBox');
  52. box.innerHTML = `<img src="${src}">`;
  53. box.style.display = 'block';
  54. }
  55. function hidePreview() {
  56. document.getElementById('previewBox').style.display = 'none';
  57. }