/
edit.tsx
116 lines (105 loc) · 3.07 KB
/
edit.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import dynamic from "next/dynamic";
import React from "react";
import { useState, useRef, useEffect } from "react";
import reactCSS from "reactcss";
import { SketchPicker, ColorResult } from "react-color";
import useHostChannel from "@/hooks/useHostChannel";
import { Color, Config } from "@/helpers/types";
import { colord } from "colord";
const ColorSummary = dynamic(() => import("@/components/ColorSummary"), {
loading: () => <p>Loading...</p>,
});
const DEFAULT_COLOR = "#ffffff";
export default function Component() {
const colorRef = useRef<HTMLDivElement>(null);
const [color, setColor] = useState<Color | undefined>();
const [config, setConfig] = useState<Config>({});
const hostChannel = useHostChannel({
onMessage(message) {
switch (message.type) {
case "connected": {
hostChannel.sendMessage({ type: "get:field-value" });
hostChannel.sendMessage({ type: "get:field-config" });
hostChannel.sendMessage({ type: "get:field-context" });
hostChannel.sendMessage({
type: "set:style",
data: {
height: "350px",
},
});
hostChannel.sendMessage({
type: "get:mode",
});
return;
}
case "field-value": {
if (message?.data?.color) setColor(message?.data?.color);
return;
}
case "field-config": {
setConfig(message.data ?? {});
return;
}
case "mode": {
console.log("From edit component: The current mode is", message.data);
return;
}
case "field-context": {
const { taskId, contentGuid } = message.data;
console.log(`Task ID ${taskId} & Content GUID ${contentGuid}`);
return;
}
}
},
});
const handleClose = () => {
hostChannel.sendMessage({
type: "set:field-value",
data: color ? { color } : undefined,
});
hostChannel.sendMessage({ type: "set:mode", data: "view" });
};
const handleChange = (color: ColorResult) => {
const c = color.rgb;
const hex = colord(`rgba(${c.r}, ${c.g}, ${c.b}, ${c.a})`).toHex();
setColor(hex);
};
const styles = reactCSS({
default: {
popover: {
position: "absolute" as "absolute",
zIndex: 2,
},
cover: {
position: "fixed" as "fixed",
top: "0px",
right: "0px",
bottom: "0px",
left: "0px",
},
},
});
useEffect(() => {
if (color) {
return;
}
const shade = config.shade ?? "";
if (shade == "red") {
setColor("#ff0000");
} else if (shade == "blue") {
setColor("#0000ff");
} else if (shade == "green") {
setColor("#00ff00");
}
}, [color, config]);
const displayColor = color ?? DEFAULT_COLOR;
return (
<div ref={colorRef}>
<ColorSummary color={color} onClick={() => {}} />
<div style={styles.popover}>
<div style={styles.cover} onClick={handleClose} />
<SketchPicker color={displayColor} onChange={handleChange} />
</div>
</div>
);
}