|
| 1 | +document.addEventListener("DOMContentLoaded", () => { |
| 2 | + const buttons = document.querySelectorAll(".hwp-previews-insert-tag"); |
| 3 | + const input = document.querySelector(".hwp-previews-url"); |
| 4 | + |
| 5 | + function setTouched() { |
| 6 | + this.setAttribute("data-touched", "true"); |
| 7 | + this.removeEventListener("focus", setTouched); |
| 8 | + } |
| 9 | + |
| 10 | + function insertTag() { |
| 11 | + const tag = this.textContent.trim(); |
| 12 | + const isTouched = input.dataset.touched; |
| 13 | + |
| 14 | + if (!input) return; |
| 15 | + |
| 16 | + // Get cursor position |
| 17 | + let cursorPos = input.selectionEnd; |
| 18 | + |
| 19 | + // If cursor position is at the start, set it to the end of the input value |
| 20 | + if (cursorPos === 0 && !isTouched) cursorPos = input.value.length; |
| 21 | + |
| 22 | + // Split text at cursor position |
| 23 | + const textBefore = input.value.substring(0, cursorPos); |
| 24 | + const textAfter = input.value.substring(cursorPos); |
| 25 | + |
| 26 | + // Insert link text at cursor position |
| 27 | + input.value = textBefore + tag + textAfter; |
| 28 | + |
| 29 | + // Set cursor position after inserted text |
| 30 | + const newCursorPos = cursorPos + tag.length; |
| 31 | + input.setSelectionRange(newCursorPos, newCursorPos); |
| 32 | + |
| 33 | + // Focus the input |
| 34 | + input.focus(); |
| 35 | + } |
| 36 | + |
| 37 | + // Mark the input as touched to prevent inserting at the start |
| 38 | + input.addEventListener("focus", setTouched); |
| 39 | + |
| 40 | + for (const button of buttons) { |
| 41 | + button.addEventListener("click", insertTag); |
| 42 | + } |
| 43 | +}); |
0 commit comments