Skip to content

Commit 6fbf1e1

Browse files
authored
context menu color addon -- gradient support
1 parent 6431e6b commit 6fbf1e1

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/addons/addons/editor-colored-context-menus/userscript.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,35 @@ import { removeAlpha } from "../../libraries/common/cs/text-color.esm.js";
33
export default async function ({ addon, console }) {
44
const ScratchBlocks = await addon.tab.traps.getBlockly();
55

6+
const fixupColor = (color) => {
7+
// some extensions have SVG-gradient styled blocks
8+
if (color.startsWith(`url(#`)) {
9+
const gradientID = color.substring(5, color.length - 1);
10+
const gradientCode = document.querySelector(`svg [id="${gradientID}"]`);
11+
if (!gradientCode || gradientCode.tagName !== "linearGradient") return [0, "#000000"];
12+
13+
const parseCoord = v => parseFloat(v.replace("%", ""));
14+
const x1 = parseCoord(gradientCode.getAttribute("x1") || "0");
15+
const y1 = parseCoord(gradientCode.getAttribute("y1") || "0");
16+
const x2 = parseCoord(gradientCode.getAttribute("x2") || "100");
17+
const y2 = parseCoord(gradientCode.getAttribute("y2") || "0");
18+
19+
const dx = x2 - x1, dy = y2 - y1;
20+
const angleDeg = ((Math.atan2(dy, dx) * 180) / Math.PI + 90 + 360) % 360;
21+
22+
const stops = Array.from(gradientCode.querySelectorAll("stop")).map(stop => {
23+
const color = stop.getAttribute("stop-color") || "#000";
24+
let offset = stop.getAttribute("offset");
25+
if (!offset) offset = "0%";
26+
else if (!offset.endsWith("%")) offset = parseFloat(offset) * 100 + "%";
27+
return `${color} ${offset}`;
28+
});
29+
return [1, `linear-gradient(${angleDeg.toFixed(2)}deg, ${stops.join(", ")})`];
30+
} else {
31+
return [0, removeAlpha(color)];
32+
}
33+
};
34+
635
const applyContextMenuColor = (block) => {
736
const widgetDiv = ScratchBlocks.WidgetDiv.DIV;
837
if (!widgetDiv) {
@@ -12,7 +41,7 @@ export default async function ({ addon, console }) {
1241
if (!background) {
1342
return;
1443
}
15-
const fill = removeAlpha(background.getAttribute("fill"));
44+
const fill = fixupColor(background.getAttribute("fill"));
1645
const border = background.getAttribute("stroke") || "#0003";
1746
widgetDiv.classList.add("sa-contextmenu-colored");
1847
widgetDiv.style.setProperty("--sa-contextmenu-bg", fill);

0 commit comments

Comments
 (0)