|
| 1 | +export default async function ({ feature, console }) { |
| 2 | + const availableWidth = 405; |
| 3 | + |
| 4 | + function getSpaceWidth() { |
| 5 | + const span = document.createElement("span"); |
| 6 | + span.style.visibility = "hidden"; |
| 7 | + span.style.whiteSpace = "pre"; |
| 8 | + span.textContent = " "; |
| 9 | + document.body.appendChild(span); |
| 10 | + const spaceWidth = span.getBoundingClientRect().width; |
| 11 | + document.body.removeChild(span); |
| 12 | + return spaceWidth; |
| 13 | + } |
| 14 | + |
| 15 | + function getTextWidth(text) { |
| 16 | + const span = document.createElement("span"); |
| 17 | + span.style.visibility = "hidden"; |
| 18 | + span.style.whiteSpace = "pre"; |
| 19 | + span.textContent = text; |
| 20 | + document.body.appendChild(span); |
| 21 | + const textWidth = span.getBoundingClientRect().width; |
| 22 | + document.body.removeChild(span); |
| 23 | + return textWidth; |
| 24 | + } |
| 25 | + |
| 26 | + function centerAlignText() { |
| 27 | + const form = document.querySelector(".project-description-form"); |
| 28 | + if (form) { |
| 29 | + const activeElement = document.activeElement; |
| 30 | + if ( |
| 31 | + activeElement.tagName === "TEXTAREA" && |
| 32 | + form.contains(activeElement) |
| 33 | + ) { |
| 34 | + const spaceWidth = getSpaceWidth(); |
| 35 | + const lines = activeElement.value.split("\n"); |
| 36 | + const centeredLines = lines.map((line) => { |
| 37 | + const textWidth = getTextWidth(line); |
| 38 | + const totalSpaces = (availableWidth - textWidth) / spaceWidth / 2; |
| 39 | + const spaces = " ".repeat(Math.floor(totalSpaces)); |
| 40 | + return spaces + line; |
| 41 | + }); |
| 42 | + activeElement.value = centeredLines.join("\n"); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + window.addEventListener("keydown", (event) => { |
| 48 | + if ((event.ctrlKey || event.metaKey) && event.key === "u") { |
| 49 | + centerAlignText(); |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + await ScratchTools.waitForElements( |
| 54 | + ".project-description-form textarea", |
| 55 | + (textareas) => { |
| 56 | + textareas.forEach((textarea) => { |
| 57 | + textarea.addEventListener("input", function () { |
| 58 | + centerAlignText(); |
| 59 | + }); |
| 60 | + }); |
| 61 | + } |
| 62 | + ); |
| 63 | +} |
0 commit comments