Skip to content

Commit 1566d77

Browse files
authored
Align to Center
1 parent 0276052 commit 1566d77

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

features/align-to-center/data.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"title": "Align to Center",
3+
"description": "Use Control + U / Command + U to center text within the instruction box on projects",
4+
"credits": [
5+
{
6+
"username": "Brass_Glass",
7+
"url": "https://scratch.mit.edu/users/Brass_Glass/"
8+
},
9+
{
10+
"username": "MaterArc",
11+
"url": "https://scratch.mit.edu/users/MaterArc/"
12+
}
13+
],
14+
"type": ["Website"],
15+
"tags": ["New", "Recommended"],
16+
"dynamic": true,
17+
"scripts": [{ "file": "script.js", "runOn": "/projects/*" }]
18+
}

features/align-to-center/script.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)