Skip to content

Commit 97492c6

Browse files
committed
优化颜色选择器对 HEX 的支持
1 parent 37e7c74 commit 97492c6

File tree

2 files changed

+32
-11
lines changed

2 files changed

+32
-11
lines changed

src/editor/inputs/subblocks/coloUtils.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
11
export function nameToHex(name: string) {
2+
if (name.startsWith("#") || name.startsWith("rgb")) return undefined;
23
const hex = colorNames[name.toLowerCase() as keyof typeof colorNames];
34
if (hex) return hex;
45
return undefined;
56
}
67

8+
export function hexToRgba(hex: string) {
9+
if (hex.startsWith("#")) {
10+
hex = hex.slice(1);
11+
}
12+
if (hex.length === 3 || hex.length === 4)
13+
hex = [...hex].map((c) => c + c).join("");
14+
if (hex.length === 6) hex += "FF";
15+
const bigint = parseInt(hex, 16);
16+
const r = (bigint >> 24) & 255;
17+
const g = (bigint >> 16) & 255;
18+
const b = (bigint >> 8) & 255;
19+
const a = bigint & 255;
20+
if (a === 255) return `rgb(${r}, ${g}, ${b})`;
21+
return `rgba(${r}, ${g}, ${b}, ${a / 255})`;
22+
}
23+
724
const colorNames = {
825
aliceblue: "#f0f8ff",
926
antiquewhite: "#faebd7",

src/editor/inputs/subblocks/colorPicker.vue

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
<template>
22
<s-text-field class="input monospace" label="颜色" v-model.trim="color">
3-
<s-popup slot="end" align="right" ref="popup" @show="pickerKey = Symbol()">
3+
<s-popup slot="end" ref="popup" @show="pickerKey = Symbol()">
44
<s-icon-button
55
slot="trigger"
66
class="colorpicker-button"
77
:style="{ color }"
88
>
99
<SIconPalette />
1010
</s-icon-button>
11-
<ColorPicker
12-
:color="processedColor"
13-
sucker-hide
14-
@changeColor="changeColor"
15-
:key="pickerKey"
16-
/>
11+
<div class="colorpicker-popup-shell">
12+
<ColorPicker
13+
:color="processedColor"
14+
sucker-hide
15+
@changeColor="changeColor"
16+
:key="pickerKey"
17+
/>
18+
</div>
1719
</s-popup>
1820
</s-text-field>
1921
</template>
2022

2123
<script lang="ts" setup>
22-
import { nameToHex } from "./coloUtils";
24+
import { hexToRgba, nameToHex } from "./coloUtils";
2325
import SIconPalette from "@/ui/icons/palette.vue";
2426
import { computed, ref } from "vue";
2527
import { ColorPicker } from "vue-color-kit";
@@ -33,9 +35,11 @@ interface ColorPickerArgs {
3335
}
3436
3537
const processedColor = computed(() => {
36-
const colorstr = color.value.trim() || "#4682B4";
37-
if (colorstr.startsWith("#") || colorstr.startsWith("rgb")) return colorstr;
38-
return nameToHex(colorstr) ?? colorstr;
38+
let colorstr = color.value.trim() || "#4682B4";
39+
colorstr = nameToHex(colorstr) ?? colorstr;
40+
if (colorstr.startsWith("rgb")) return colorstr;
41+
if (colorstr.startsWith("#")) return hexToRgba(colorstr);
42+
return colorstr;
3943
});
4044
4145
function changeColor(newColor: ColorPickerArgs) {

0 commit comments

Comments
 (0)