Skip to content

Commit 21a4c10

Browse files
authored
Svg color preview (#1135)
* feat: add color preview support in svg files(#1134)
1 parent e53ea06 commit 21a4c10

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

src/ace/colorView.js

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
/**
2-
* This piece of code belongs to github.com/easylogic and is licensed under MIT
2+
* Some part of this code belongs to github.com/easylogic and is licensed under MIT
33
* @see https://github.com/easylogic/ace-colorpicker/blob/main/src/extension/ace/colorview.js
44
*/
55

66
import Color from "utils/color";
7-
import { HEX, HSL, HSLA, RGB, RGBA, isValidColor } from "utils/color/regex";
7+
import {
8+
HEX,
9+
HSL,
10+
HSLA,
11+
NAMED_COLORS,
12+
RGB,
13+
RGBA,
14+
isValidColor,
15+
} from "utils/color/regex";
816

917
const COLORPICKER_TOKEN_CLASS = ".ace_color";
1018
const changedRules = [];
@@ -56,7 +64,7 @@ export function deactivateColorView() {
5664
*/
5765
function sessionSupportsColor(session) {
5866
const mode = session.getMode().$id.split("/").pop();
59-
return /css|less|scss|sass|stylus|html|dart/.test(mode) ? mode : false;
67+
return /css|less|scss|sass|stylus|html|svg|dart/.test(mode) ? mode : false;
6068
}
6169

6270
function onChangeMode() {
@@ -75,6 +83,29 @@ function onChangeMode() {
7583
rules = { ruleset: rules["ruleset"] };
7684
} else if (mode === "html") {
7785
rules = { "css-ruleset": rules["css-ruleset"] };
86+
} else if (mode === "svg") {
87+
const svgColorAttrs = [
88+
"fill",
89+
"stroke",
90+
"stop-color",
91+
"flood-color",
92+
"lighting-color",
93+
];
94+
Object.keys(rules).forEach((key) => {
95+
const rule = rules[key];
96+
if (Array.isArray(rule)) {
97+
rule.unshift({
98+
token: "color",
99+
regex: `(?<=\\b(?:${svgColorAttrs.join("|")})\\s*=\\s*["'])(${HEX}|${RGB}|${RGBA}|${HSL}|${HSLA}|\\w+)(?=["'])`,
100+
});
101+
rule.unshift({
102+
token: "color",
103+
regex: `(?<=style\\s*=\\s*["'][^"']*(?:${svgColorAttrs.join("|")})\\s*:\\s*)(${HEX}|${RGB}|${RGBA}|${HSL}|${HSLA}|\\w+)(?=\\s*[;'"])`,
104+
});
105+
changedRules.push(rule);
106+
forceUpdate = true;
107+
}
108+
});
78109
}
79110

80111
Object.keys(rules).forEach((key) => {
@@ -125,6 +156,10 @@ function afterRender() {
125156
if (el.dataset.modified === "true") return;
126157
el.dataset.modified = "true";
127158

159+
if (mode === "svg" && content in NAMED_COLORS) {
160+
content = NAMED_COLORS[content];
161+
}
162+
128163
if (!isValidColor(content)) {
129164
if (isValidColor(multiLinePrev)) {
130165
content = multiLinePrev;

0 commit comments

Comments
 (0)