-
Notifications
You must be signed in to change notification settings - Fork 769
/
ThemeColorPicker.tsx
248 lines (218 loc) · 8.52 KB
/
ThemeColorPicker.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/*
* @author Stéphane LaFlèche <stephane.l@vanillaforums.com>
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import Button from "@library/forms/Button";
import { ButtonTypes } from "@library/forms/buttonTypes";
import { themeBuilderClasses } from "@library/forms/themeEditor/ThemeBuilder.styles";
import { useThemeBlock } from "@library/forms/themeEditor/ThemeBuilderBlock";
import { useThemeVariableField } from "@library/forms/themeEditor/ThemeBuilderContext";
import { colorPickerClasses } from "@library/forms/themeEditor/ThemeColorPicker.styles";
import { ensureColorHelper } from "@library/styles/styleHelpers";
import { visibility } from "@library/styles/styleHelpersVisibility";
import { stringIsValidColor } from "@library/styles/styleUtils";
import { useUniqueID } from "@library/utility/idUtils";
import { t } from "@vanilla/i18n/src";
import classNames from "classnames";
import debounce from "lodash/debounce";
import React, { useCallback, useEffect, useRef, useState, useLayoutEffect } from "react";
import { ThemeBuilderRevert } from "@library/forms/themeEditor/ThemeBuilderRevert";
import Pickr from "@simonwep/pickr";
import "./ThemeColorPicker.scss";
import ScreenReaderContent from "@library/layout/ScreenReaderContent";
interface IProps extends Omit<React.HTMLAttributes<HTMLInputElement>, "type" | "id" | "tabIndex"> {
variableKey: string;
inputClass?: string;
}
export function ThemeColorPicker(_props: IProps) {
const { variableKey, inputClass, ...inputProps } = _props;
const { inputID, labelID } = useThemeBlock();
// The field
const { generatedValue, initialValue, rawValue, defaultValue, setValue, error, setError } = useThemeVariableField(
variableKey,
);
const classes = colorPickerClasses();
const colorInput = useRef<HTMLInputElement>(null);
const textInput = useRef<HTMLInputElement>(null);
const builderClasses = themeBuilderClasses();
const errorID = useUniqueID("colorPickerError");
// Track whether we have a valid color.
// If the color is not set, we don't really care.
const [textInputValue, setTextFieldValue] = useState<string | null>(rawValue);
const [lastValidColor, setLastValidColor] = useState<string | null>(rawValue ?? null);
useEffect(() => {
setTextFieldValue(rawValue);
}, [rawValue, setTextFieldValue]);
// If we have no color selected we are displaying the default and are definitely valid.
const isValidColor = textInputValue ? stringIsValidColor(textInputValue) : true;
// Do initial load validation of the color.
useEffect(() => {
if (!isValidColor) {
setError(t("Invalid Color"));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleColorChange = (colorString: string) => {
setTextFieldValue(colorString);
if (colorString === "") {
// we are clearing our color to the default.
setValue(colorString);
setLastValidColor(defaultValue);
} else if (stringIsValidColor(colorString)) {
setValue(colorString); // Only set valid color if passes validation
setLastValidColor(colorString);
} else {
setError(t("Invalid Color"));
}
};
// Handle updates from the text field.
const onTextChange = e => {
const colorString = e.target.value;
handleColorChange(colorString);
};
const handleColorChangeRef = useRef<typeof handleColorChange>(handleColorChange);
// Debounced internal function for onPickerChange.
// Be sure to always use it through the following ref so that we the function identitity,
// While still preserving the debounce.
// This article explains the issue being worked around here https://dmitripavlutin.com/react-hooks-stale-closures/
const _debouncedPickerUpdate = useCallback(
debounce(
(colorString: string) => {
handleColorChangeRef.current(colorString);
},
16,
{ trailing: true },
),
[],
);
// Handle updates from the color picker.
const onPickerChange = (newColor: string) => {
// Will always be valid color, since it's a real picker
if (newColor) {
handleColorChangeRef.current = handleColorChange;
_debouncedPickerUpdate(newColor);
}
};
const defaultColorString = ensureColorHelper(generatedValue).toHexString();
const validColorString = lastValidColor ? ensureColorHelper(lastValidColor).toHexString() : defaultColorString;
return (
<>
<span className={classes.root}>
{/*Text Input*/}
<input
ref={textInput}
type="text"
aria-describedby={labelID}
aria-hidden={true}
className={classNames(classes.textInput, {
[builderClasses.invalidField]: !!error,
})}
placeholder={defaultColorString}
value={textInputValue ?? ""} // Null is not an allowed value for an input.
onChange={onTextChange}
auto-correct="false"
/>
<Picker onChange={onPickerChange} validColorString={validColorString} />
</span>
<ThemeBuilderRevert variableKey={variableKey} />
{error && (
<ul id={errorID} className={builderClasses.errorContainer}>
<li className={builderClasses.error}>{error}</li>
</ul>
)}
</>
);
}
function Picker(props: { onChange: (newColor: string) => void; validColorString: string }) {
const ref = useRef<HTMLButtonElement>(null);
const pickrRef = useRef<Pickr | null>(null);
const { onChange, validColorString } = props;
const classes = colorPickerClasses();
const currentColorRef = useRef(validColorString);
useEffect(() => {
currentColorRef.current = validColorString;
}, [validColorString]);
const handleChange = useCallback(
(color: Pickr.HSVaColor) => {
const finalColor = color.toHEXA().toString();
onChange(finalColor);
},
[onChange],
);
const changeHandlerRef = useRef<typeof handleChange | null>(null);
useEffect(() => {
if (changeHandlerRef.current) {
pickrRef.current?.off("change", changeHandlerRef.current);
}
changeHandlerRef.current = handleChange;
pickrRef.current?.on("change", handleChange);
return () => {
pickrRef.current?.off("change", handleChange);
};
}, [handleChange]);
const createAndOpen = useCallback(() => {
if (!ref.current) {
return;
}
if (pickrRef.current) {
return;
}
const pickr = Pickr.create({
el: ref.current,
theme: "nano",
outputPrecision: 0,
useAsButton: true,
default: currentColorRef.current,
components: {
// Main components
preview: true,
hue: true,
// Input / output Options
interaction: {
input: true,
},
},
});
pickr.show();
pickrRef.current = pickr;
pickrRef.current?.on("change", handleChange);
changeHandlerRef.current = handleChange;
}, [handleChange]);
useEffect(() => {
return () => {
pickrRef.current?.destroy();
pickrRef.current = null;
};
}, []);
useEffect(() => {
pickrRef.current?.setColor(validColorString, true);
}, [validColorString]);
useEffect(() => {
const handler = () => {
if (document.activeElement?.tagName === "IFRAME") {
pickrRef.current?.hide();
}
};
window.addEventListener("blur", handler);
return () => {
window.removeEventListener("blur", handler);
};
}, []);
return (
<Button
buttonRef={ref}
onClick={() => {
createAndOpen();
}}
style={{ backgroundColor: props.validColorString }}
title={props.validColorString}
aria-hidden={true}
className={classes.swatch}
tabIndex={-1}
baseClass={ButtonTypes.CUSTOM}
>
<ScreenReaderContent>{props.validColorString}</ScreenReaderContent>
</Button>
);
}