plotboilerplate 1.24.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +13 -1
  2. package/dist/index.esm.js +294 -129
  3. package/dist/index.esm.js.map +1 -1
  4. package/dist/index.esm.min.js +1 -1
  5. package/dist/index.esm.min.js.map +1 -1
  6. package/dist/plotboilerplate.browser.min.js +1 -1
  7. package/dist/plotboilerplate.browser.min.js.map +1 -1
  8. package/dist/plotboilerplate.js +12084 -11919
  9. package/dist/plotboilerplate.min.js +1 -1
  10. package/package.json +9 -5
  11. package/src/cjs/PlotBoilerplate.d.ts +37 -6
  12. package/src/cjs/PlotBoilerplate.js +222 -116
  13. package/src/cjs/PlotBoilerplate.js.map +1 -1
  14. package/src/cjs/Polygon.d.ts +26 -7
  15. package/src/cjs/Polygon.js +56 -10
  16. package/src/cjs/Polygon.js.map +1 -1
  17. package/src/cjs/Triangle.js +2 -2
  18. package/src/cjs/Triangle.js.map +1 -1
  19. package/src/cjs/Vertex.d.ts +15 -3
  20. package/src/cjs/Vertex.js +18 -1
  21. package/src/cjs/Vertex.js.map +1 -1
  22. package/src/cjs/interfaces/core.d.ts +28 -0
  23. package/src/cjs/interfaces/core.js +2 -0
  24. package/src/cjs/interfaces/core.js.map +1 -1
  25. package/src/cjs/utils/datastructures/Color.d.ts +147 -1
  26. package/src/cjs/utils/datastructures/Color.js +385 -41
  27. package/src/cjs/utils/datastructures/Color.js.map +1 -1
  28. package/src/cjs/utils/datastructures/ColorGradient.d.ts +79 -0
  29. package/src/cjs/utils/datastructures/ColorGradient.js +171 -0
  30. package/src/cjs/utils/datastructures/ColorGradient.js.map +1 -0
  31. package/src/cjs/utils/dom/components/ColorGradientPicker.d.ts +245 -0
  32. package/src/cjs/utils/dom/components/ColorGradientPicker.js +667 -0
  33. package/src/cjs/utils/dom/components/ColorGradientPicker.js.map +1 -0
  34. package/src/cjs/utils/dom/components/ColorGradientPickerJSX.d.ts +129 -0
  35. package/src/cjs/utils/dom/components/ColorGradientPickerJSX.js +520 -0
  36. package/src/cjs/utils/dom/components/ColorGradientPickerJSX.js.map +1 -0
  37. package/src/cjs/utils/dom/components/ColorGradientSelector.d.ts +117 -0
  38. package/src/cjs/utils/dom/components/ColorGradientSelector.js +325 -0
  39. package/src/cjs/utils/dom/components/ColorGradientSelector.js.map +1 -0
  40. package/src/cjs/utils/dom/components/Test.d.ts +7 -0
  41. package/src/cjs/utils/dom/components/Test.js +30 -0
  42. package/src/cjs/utils/dom/components/Test.js.map +1 -0
  43. package/src/cjs/utils/dom/guiSizeToggler.js +1 -1
  44. package/src/cjs/utils/dom/guiSizeToggler.js.map +1 -1
  45. package/src/cjs/utils/helpers/BezierPathInteractionHelper.d.ts +9 -3
  46. package/src/cjs/utils/helpers/BezierPathInteractionHelper.js +20 -13
  47. package/src/cjs/utils/helpers/BezierPathInteractionHelper.js.map +1 -1
  48. package/src/cjs/utils/helpers/CircleHelper.d.ts +10 -1
  49. package/src/cjs/utils/helpers/CircleHelper.js +13 -2
  50. package/src/cjs/utils/helpers/CircleHelper.js.map +1 -1
  51. package/src/cjs/utils/helpers/CircleSectorHelper.d.ts +2 -2
  52. package/src/cjs/utils/helpers/CircleSectorHelper.js +1 -0
  53. package/src/cjs/utils/helpers/CircleSectorHelper.js.map +1 -1
  54. package/src/cjs/utils/helpers/TriangleHelper.d.ts +57 -0
  55. package/src/cjs/utils/helpers/TriangleHelper.js +83 -0
  56. package/src/cjs/utils/helpers/TriangleHelper.js.map +1 -0
  57. package/src/cjs/utils/helpers/VEllipseHelper.d.ts +6 -4
  58. package/src/cjs/utils/helpers/VEllipseHelper.js +4 -2
  59. package/src/cjs/utils/helpers/VEllipseHelper.js.map +1 -1
  60. package/src/cjs/utils/helpers/VEllipseSectorHelper.d.ts +3 -2
  61. package/src/cjs/utils/helpers/VEllipseSectorHelper.js +1 -0
  62. package/src/cjs/utils/helpers/VEllipseSectorHelper.js.map +1 -1
  63. package/src/cjs/utils/parsers/LinearColorGradientParser.d.ts +78 -0
  64. package/src/cjs/utils/parsers/LinearColorGradientParser.js +224 -0
  65. package/src/cjs/utils/parsers/LinearColorGradientParser.js.map +1 -0
  66. package/src/createDemoDrawables.js +1 -0
  67. package/src/esm/PlotBoilerplate.d.ts +37 -6
  68. package/src/esm/PlotBoilerplate.js +222 -116
  69. package/src/esm/PlotBoilerplate.js.map +1 -1
  70. package/src/esm/Polygon.d.ts +26 -7
  71. package/src/esm/Polygon.js +53 -10
  72. package/src/esm/Polygon.js.map +1 -1
  73. package/src/esm/Triangle.js +2 -2
  74. package/src/esm/Triangle.js.map +1 -1
  75. package/src/esm/Vertex.d.ts +15 -3
  76. package/src/esm/Vertex.js +18 -1
  77. package/src/esm/Vertex.js.map +1 -1
  78. package/src/esm/interfaces/core.d.ts +28 -0
  79. package/src/esm/interfaces/core.js +2 -0
  80. package/src/esm/interfaces/core.js.map +1 -1
  81. package/src/esm/utils/datastructures/Color.d.ts +147 -1
  82. package/src/esm/utils/datastructures/Color.js +386 -42
  83. package/src/esm/utils/datastructures/Color.js.map +1 -1
  84. package/src/esm/utils/datastructures/ColorGradient.d.ts +79 -0
  85. package/src/esm/utils/datastructures/ColorGradient.js +166 -0
  86. package/src/esm/utils/datastructures/ColorGradient.js.map +1 -0
  87. package/src/esm/utils/dom/components/ColorGradientPicker.d.ts +245 -0
  88. package/src/esm/utils/dom/components/ColorGradientPicker.js +732 -0
  89. package/src/esm/utils/dom/components/ColorGradientPicker.js.map +1 -0
  90. package/src/esm/utils/dom/components/ColorGradientPickerJSX.d.ts +129 -0
  91. package/src/esm/utils/dom/components/ColorGradientPickerJSX.js +582 -0
  92. package/src/esm/utils/dom/components/ColorGradientPickerJSX.js.map +1 -0
  93. package/src/esm/utils/dom/components/ColorGradientSelector.d.ts +117 -0
  94. package/src/esm/utils/dom/components/ColorGradientSelector.js +332 -0
  95. package/src/esm/utils/dom/components/ColorGradientSelector.js.map +1 -0
  96. package/src/esm/utils/dom/components/Test.d.ts +7 -0
  97. package/src/esm/utils/dom/components/Test.js +26 -0
  98. package/src/esm/utils/dom/components/Test.js.map +1 -0
  99. package/src/esm/utils/dom/guiSizeToggler.js +1 -1
  100. package/src/esm/utils/dom/guiSizeToggler.js.map +1 -1
  101. package/src/esm/utils/helpers/BezierPathInteractionHelper.d.ts +9 -3
  102. package/src/esm/utils/helpers/BezierPathInteractionHelper.js +20 -13
  103. package/src/esm/utils/helpers/BezierPathInteractionHelper.js.map +1 -1
  104. package/src/esm/utils/helpers/CircleHelper.d.ts +10 -1
  105. package/src/esm/utils/helpers/CircleHelper.js +13 -2
  106. package/src/esm/utils/helpers/CircleHelper.js.map +1 -1
  107. package/src/esm/utils/helpers/CircleSectorHelper.d.ts +2 -2
  108. package/src/esm/utils/helpers/CircleSectorHelper.js +1 -0
  109. package/src/esm/utils/helpers/CircleSectorHelper.js.map +1 -1
  110. package/src/esm/utils/helpers/TriangleHelper.d.ts +57 -0
  111. package/src/esm/utils/helpers/TriangleHelper.js +78 -0
  112. package/src/esm/utils/helpers/TriangleHelper.js.map +1 -0
  113. package/src/esm/utils/helpers/VEllipseHelper.d.ts +6 -4
  114. package/src/esm/utils/helpers/VEllipseHelper.js +4 -2
  115. package/src/esm/utils/helpers/VEllipseHelper.js.map +1 -1
  116. package/src/esm/utils/helpers/VEllipseSectorHelper.d.ts +3 -2
  117. package/src/esm/utils/helpers/VEllipseSectorHelper.js +1 -0
  118. package/src/esm/utils/helpers/VEllipseSectorHelper.js.map +1 -1
  119. package/src/esm/utils/parsers/LinearColorGradientParser.d.ts +78 -0
  120. package/src/esm/utils/parsers/LinearColorGradientParser.js +217 -0
  121. package/src/esm/utils/parsers/LinearColorGradientParser.js.map +1 -0
  122. package/src/external.d.ts +9 -0
  123. package/src/ts/PlotBoilerplate.ts +233 -105
  124. package/src/ts/Polygon.ts +68 -14
  125. package/src/ts/Triangle.ts +2 -2
  126. package/src/ts/Vertex.ts +21 -3
  127. package/src/ts/interfaces/core.ts +31 -0
  128. package/src/ts/utils/datastructures/Color.ts +423 -44
  129. package/src/ts/utils/datastructures/ColorGradient.ts +196 -0
  130. package/src/ts/utils/dom/components/ColorGradientPicker.tsx +877 -0
  131. package/src/ts/utils/dom/components/ColorGradientSelector.tsx +445 -0
  132. package/src/ts/utils/dom/components/Test.tsx +44 -0
  133. package/src/ts/utils/dom/components/_ColorGradientPicker_raw.ts_ +392 -0
  134. package/src/ts/utils/dom/guiSizeToggler.ts +1 -1
  135. package/src/ts/utils/helpers/BezierPathInteractionHelper.ts +25 -15
  136. package/src/ts/utils/helpers/CircleHelper.ts +17 -3
  137. package/src/ts/utils/helpers/CircleSectorHelper.ts +4 -2
  138. package/src/ts/utils/helpers/TriangleHelper.ts +102 -0
  139. package/src/ts/utils/helpers/VEllipseHelper.ts +6 -4
  140. package/src/ts/utils/helpers/VEllipseSectorHelper.ts +3 -2
  141. package/src/ts/utils/parsers/LinearColorGradientParser.ts +297 -0
@@ -0,0 +1,877 @@
1
+ /**
2
+ * Approach for a 'simple' color gradient picker for my PlotBoilerplate library.
3
+ *
4
+ * As it turned out a bit more complex in the end – due to the fact that color gradient
5
+ * picking is not a super simple task – so I used JSX here. Thus a JSX library is required
6
+ * to get this running: NoReact.
7
+ *
8
+ *
9
+ * @author Ikaros Kappler
10
+ * @date 2025-06-27
11
+ * @version 1.0.0
12
+ */
13
+
14
+ import * as NoReact from "noreact";
15
+ import { JsxElement } from "typescript";
16
+
17
+ import { Color } from "../../datastructures/Color";
18
+ import { ColorGradient, ColorGradientItem } from "../../datastructures/ColorGradient";
19
+
20
+ export type ColorGradientChangeListener = (colorGradient: ColorGradient, source: ColorGradientPicker) => void;
21
+
22
+ export class ColorGradientPicker {
23
+ private readonly baseID: number;
24
+ private readonly elementID: string;
25
+
26
+ private container: HTMLElement;
27
+ private containerRef: NoReact.Ref<HTMLDivElement>;
28
+ private _sliderElementRefs: Array<NoReact.Ref<HTMLInputElement>> = [];
29
+ private colorInputRef: NoReact.Ref<HTMLInputElement>;
30
+ private colorIndicatorColorButtonRef: NoReact.Ref<HTMLButtonElement>;
31
+ private colorIndicatorRemoveButtonRef: NoReact.Ref<HTMLButtonElement>;
32
+ private colorInputContainerRef: NoReact.Ref<HTMLDivElement>;
33
+ private sliderMin: number = 0;
34
+ private sliderMax: number = 100;
35
+
36
+ // Only used during initialization!
37
+
38
+ private isMobileMode: boolean = false;
39
+ private css_indicatorWidth_num = 1.0;
40
+ private css_indicatorWidth = "1em";
41
+ private css_indicatorHeight = "1em";
42
+ private css_thumbWidth = "0.5em";
43
+ private css_thumbHeight = "1.333em";
44
+ private css_containerHeight = "20px";
45
+
46
+ private colorGradient: ColorGradient;
47
+
48
+ private installedChangeListeners: Array<ColorGradientChangeListener> = [];
49
+
50
+ private __mouseDownPosition: { x: number; y: number } = null;
51
+
52
+ /**
53
+ * The constructor: creates a new color gradient picker in the given container.
54
+ * If no container or ID is given then a new unbound `container` will be created (DIV).
55
+ *
56
+ * Pass a container ID or nothing – in the latter case the constructor will create
57
+ * a new DIV element.
58
+ *
59
+ * @param {string?} containerID - (optional) If you want to use an existing container (should be a DIV).
60
+ * @param {boolean?} isMobileMode - (optional) If `true` then the elements are rendered in double size.
61
+ */
62
+ constructor(containerID?: string, isMobileMode?: boolean) {
63
+ if (containerID) {
64
+ const cont = document.getElementById(containerID);
65
+ if (!cont) {
66
+ throw "Cannot create ColorGradientPicker. Component ID does not exist.";
67
+ }
68
+ this.container = cont;
69
+ } else {
70
+ this.container = document.createElement("div");
71
+ }
72
+ this.baseID = Math.floor(Math.random() * 65535);
73
+ this.elementID = `color-gradient-picker-${this.baseID}`;
74
+ this.colorGradient = ColorGradient.createDefault();
75
+
76
+ this.isMobileMode = Boolean(isMobileMode);
77
+ if (isMobileMode) {
78
+ // Double size :)
79
+ this.css_indicatorWidth_num = 2.0;
80
+ this.css_indicatorWidth = "2em";
81
+ this.css_indicatorHeight = "2em";
82
+ this.css_thumbWidth = "1.0em";
83
+ this.css_thumbHeight = "2.666em";
84
+ this.css_containerHeight = "40px";
85
+ }
86
+
87
+ document.head.appendChild(this.__createCustomStylesElement());
88
+ this.container.append(this._render());
89
+ this.__initializeDataSets();
90
+ this.__updateColorIndicator(0);
91
+ this.__updateBackgroundGradient();
92
+ } // END constructor
93
+
94
+ public setGradient(gradient: ColorGradient, fireChangeEvent?: boolean): void {
95
+ // We are lazy: just throw away everything and rebuild all.
96
+ this.__removeAllChildNodes(this.container);
97
+ this.colorGradient = gradient;
98
+ this.container.append(this._render());
99
+ this.__initializeDataSets();
100
+ this.__updateColorIndicator(0);
101
+ this.__updateBackgroundGradient();
102
+ if (fireChangeEvent) {
103
+ this.__fireChangeEvent();
104
+ }
105
+ }
106
+
107
+ // +---------------------------------------------------------------------------------
108
+ // | A helper function to remove all child nodes.
109
+ // +-------------------------------
110
+ private __removeAllChildNodes(node: Node) {
111
+ while (node.lastChild) {
112
+ node.removeChild(node.lastChild);
113
+ }
114
+ }
115
+
116
+ // +---------------------------------------------------------------------------------
117
+ // | Used during initialization: define dataset values for each slider.
118
+ // +-------------------------------
119
+ private __initializeDataSets() {
120
+ for (var i = 0; i < this._sliderElementRefs.length; i++) {
121
+ const sliderColor = this.colorGradient.values[i].color;
122
+ // console.log("Setting up slider color data set", i, sliderColor, sliderColor.cssRGB(), sliderColor.cssHEX());
123
+ this._sliderElementRefs[i].current.dataset.colorValue = sliderColor.cssRGB();
124
+ this._sliderElementRefs[i].current.dataset.colorValueHEX = sliderColor.cssHEX();
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Adds a new color gradient change listener to this ColorGradientPicker.
130
+ *
131
+ * @param {ColorGradientChangeListener} listener - The listener to add.
132
+ * @returns {boolean} True, if the listener was added and did not exist before.
133
+ */
134
+ addChangeListener(listener: ColorGradientChangeListener): boolean {
135
+ for (var i = 0; i < this.installedChangeListeners.length; i++) {
136
+ if (this.installedChangeListeners[i] === listener) {
137
+ return false;
138
+ }
139
+ }
140
+ this.installedChangeListeners.push(listener);
141
+ return true;
142
+ }
143
+
144
+ /**
145
+ *
146
+ * @param {ColorGradientChangeListener} listener The listener to remove.
147
+ * @returns {boolean} True, if the listener existed and has been removed.
148
+ */
149
+ removeChangeListener(listener: ColorGradientChangeListener): boolean {
150
+ for (var i = 0; i < this.installedChangeListeners.length; i++) {
151
+ if (this.installedChangeListeners[i] === listener) {
152
+ this.installedChangeListeners.splice(i, 1);
153
+ return true;
154
+ }
155
+ }
156
+ return false;
157
+ }
158
+
159
+ /**
160
+ * Fires a change event to all installed listeners.
161
+ */
162
+ private __fireChangeEvent() {
163
+ const newColorGradient = this.getColorGradient();
164
+ for (var i = 0; i < this.installedChangeListeners.length; i++) {
165
+ this.installedChangeListeners[i](newColorGradient, this);
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Creates a new color range input element.
171
+ *
172
+ * @private
173
+ * @param {number} baseID
174
+ * @param index
175
+ * @param sliderMin
176
+ * @param sliderMax
177
+ * @param initialValue
178
+ * @param initialColor
179
+ * @returns
180
+ */
181
+ private __createColorRangeInput(
182
+ index: number,
183
+ sliderMin: number,
184
+ sliderMax: number,
185
+ initialValue: number,
186
+ initialColor: Color
187
+ ): JsxElement {
188
+ const sliderHandler = this.__createSliderChangeHandler();
189
+ const ref: NoReact.Ref<HTMLInputElement> = NoReact.useRef<HTMLInputElement>();
190
+ // this._sliderElementRefs.push(ref);
191
+ this._sliderElementRefs.splice(index, 0, ref);
192
+ // console.log("new _sliderElementRefs", this._sliderElementRefs);
193
+
194
+ // Update all elements to the right of the new elelemt
195
+ this.__updateSliderDataSetIndices(index + 1);
196
+
197
+ return (
198
+ <input
199
+ id={`rage-slider-${this.baseID}-${index}`}
200
+ type="range"
201
+ min={sliderMin}
202
+ max={sliderMax}
203
+ value={initialValue}
204
+ style={{ pos: "absolute", l: "0px", t: "0px", w: "100%", h: "60%" }}
205
+ data-range-slider-index={`${index}`}
206
+ data-colorValue={initialColor.cssRGB()}
207
+ data-colorValueHEX={initialColor.cssHEX()}
208
+ onChange={sliderHandler}
209
+ onClick={sliderHandler}
210
+ ref={ref}
211
+ />
212
+ );
213
+ }
214
+
215
+ /**
216
+ * Get the absolute length of this range, in slider units.
217
+ * @returns
218
+ */
219
+ getRangeLength(): number {
220
+ return this.sliderMax - this.sliderMin;
221
+ }
222
+
223
+ /**
224
+ * Creates a callback function for range slider.
225
+ *
226
+ * @returns
227
+ */
228
+ private __createSliderChangeHandler = (): ((e: Event) => boolean) => {
229
+ const _self = this;
230
+ return (e: Event): boolean => {
231
+ const targetSlider: HTMLInputElement = e.target as HTMLInputElement;
232
+ // console.log("Clicked", targetSlider ? targetSlider.getAttribute("id") : null);
233
+ if (!targetSlider) {
234
+ return false;
235
+ }
236
+ const currentSliderValue: number = Number.parseFloat(targetSlider.value);
237
+ const rangeSliderIndexRaw: string | undefined = targetSlider.dataset["rangeSliderIndex"];
238
+ // console.log("rangeSliderIndexRaw", rangeSliderIndexRaw);
239
+ if (!rangeSliderIndexRaw) {
240
+ return false;
241
+ }
242
+ const rangeSliderIndex: number = Number.parseInt(rangeSliderIndexRaw);
243
+ var leftSliderValue = this.__getSliderValue(rangeSliderIndex - 1, _self.sliderMin);
244
+ var rightSliderValue = this.__getSliderValue(rangeSliderIndex + 1, _self.sliderMax);
245
+ if (leftSliderValue >= currentSliderValue) {
246
+ targetSlider.value = `${leftSliderValue}`;
247
+ _self.__updateBackgroundGradient();
248
+ _self.__updateColorIndicator(rangeSliderIndex);
249
+ return false;
250
+ } else if (rightSliderValue <= currentSliderValue) {
251
+ targetSlider.value = `${rightSliderValue}`;
252
+ _self.__updateBackgroundGradient();
253
+ _self.__updateColorIndicator(rangeSliderIndex);
254
+
255
+ return false;
256
+ } else {
257
+ _self.__updateBackgroundGradient();
258
+ _self.__updateColorIndicator(rangeSliderIndex);
259
+ return true;
260
+ }
261
+ };
262
+ };
263
+
264
+ /**
265
+ * Handles color value changes.
266
+ *
267
+ * @returns
268
+ */
269
+ __colorChangeHandler(): (_evt: Event) => boolean {
270
+ const _self = this;
271
+ return (_evt: Event): boolean => {
272
+ // console.log("__colorChangeHandler");
273
+ const activeSliderIndex_raw = this.colorInputRef.current.dataset.activeSliderIndex;
274
+ if (!activeSliderIndex_raw) {
275
+ console.warn(
276
+ "Cannot update color indicator; no active range slider set. This is likely a program error and should not happen."
277
+ );
278
+ return false;
279
+ }
280
+ const activeSliderIndex = Number.parseInt(activeSliderIndex_raw);
281
+ if (Number.isNaN(activeSliderIndex) || activeSliderIndex < 0 || activeSliderIndex >= _self._sliderElementRefs.length) {
282
+ console.warn(
283
+ "Cannot update color indicator; active index invalid or out of bounds. This is likely a program error and should not happen.",
284
+ activeSliderIndex
285
+ );
286
+ return false;
287
+ }
288
+
289
+ const newColor: string = _self.colorInputRef.current.value;
290
+ const rangeSlider: HTMLInputElement = _self._sliderElementRefs[activeSliderIndex].current;
291
+ rangeSlider.dataset.colorValue = newColor;
292
+ // rangeSlider.dataset["colorValue"] = newColor;
293
+ this.colorIndicatorColorButtonRef.current.style["background-color"] = newColor;
294
+ _self.__updateBackgroundGradient();
295
+ _self.__fireChangeEvent();
296
+
297
+ return true;
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Removed the current color slider from the DOM and highlights the left neighbour.
303
+ *
304
+ * @returns {boolean} True if the element could be successfully removed.
305
+ */
306
+ private __handleRemoveColor(): boolean {
307
+ // const colorInput : HTMLInputElement | null = evt.target;
308
+ // console.log("__colorChangeHandler");
309
+ const activeSliderIndex_raw = this.colorInputRef.current.dataset.activeSliderIndex;
310
+ if (!activeSliderIndex_raw) {
311
+ console.warn("Cannot remove color indicator; no active range slider set.");
312
+ return false;
313
+ }
314
+ const activeSliderIndex = Number.parseInt(activeSliderIndex_raw);
315
+ if (Number.isNaN(activeSliderIndex) || activeSliderIndex < 0 || activeSliderIndex >= this._sliderElementRefs.length) {
316
+ console.warn("Cannot remove color indicator; active index invalid or out of bounds.", activeSliderIndex);
317
+ return false;
318
+ }
319
+
320
+ if (activeSliderIndex === 0 || activeSliderIndex + 1 === this.getRangeLength()) {
321
+ console.warn("Cannot remove color indicator; leftmost and rightmost slider must not be removed.", activeSliderIndex);
322
+ return false;
323
+ }
324
+
325
+ const sliderElementRef: NoReact.Ref<HTMLInputElement> = this._sliderElementRefs[activeSliderIndex];
326
+ sliderElementRef.current.remove();
327
+ this._sliderElementRefs.splice(activeSliderIndex, 1);
328
+
329
+ // Update all elements to the right of the removed elelemt
330
+ this.__updateSliderDataSetIndices(activeSliderIndex);
331
+
332
+ // Set left element active
333
+ this.__updateColorIndicator(activeSliderIndex - 1);
334
+ this.__updateBackgroundGradient();
335
+ this.__fireChangeEvent();
336
+ return true;
337
+ }
338
+
339
+ /**
340
+ * Once a slider element was added or removed then the following indices must be updated.
341
+ *
342
+ * @param {number} startIndex - The slider index to start updating at.
343
+ */
344
+ __updateSliderDataSetIndices(startIndex: number) {
345
+ // Update all elements to the right of the new elelemt
346
+ for (var i = startIndex; i < this._sliderElementRefs.length; i++) {
347
+ this._sliderElementRefs[i].current.setAttribute("data-range-slider-index", `${i}`);
348
+ this._sliderElementRefs[i].current.setAttribute("id", `rage-slider-${this.baseID}-${i}`);
349
+ }
350
+ }
351
+
352
+ /**
353
+ * To avoid too many sliders added on each click, check if the mouse was moved in the meantime (detect drag event).
354
+ *
355
+ * @returns
356
+ */
357
+ private __containerMouseDownHandler(): (event: MouseEvent) => void {
358
+ const _self = this;
359
+ return (event: MouseEvent) => {
360
+ _self.__mouseDownPosition = { x: event.clientX, y: event.clientY };
361
+ // console.log("__containerMouseDownHandler _self.__mouseDownPosition", _self.__mouseDownPosition);
362
+ };
363
+ }
364
+
365
+ /**
366
+ * Creates a handler for click events on the container. If the click event is far
367
+ * enough from existing sliders, then it can be added.
368
+ *
369
+ * @returns
370
+ */
371
+ private __containerClickHandler(): (evt: MouseEvent) => void {
372
+ const _self = this;
373
+ const maxDifference = _self.getRangeLength() * 0.03;
374
+ return (evt: MouseEvent): void => {
375
+ // console.log("Container click handler");
376
+ const relativeValue: number = _self.__clickEventToRelativeValue(evt);
377
+ if (relativeValue < 0 || relativeValue > 1.0) {
378
+ // Clicked somewhere outside the range
379
+ return;
380
+ }
381
+
382
+ // Check if element was moved in the meantime
383
+ if (_self.__mouseDownPosition && Math.abs(_self.__mouseDownPosition.x - evt.clientX) >= 10.0) {
384
+ // Ignore event if mouse was moved more than 10 pixels between down- and up-event
385
+ // console.log("Mouse was moved more than 10 px. Cancelling.");
386
+ _self.__mouseDownPosition = null;
387
+ return;
388
+ }
389
+
390
+ const absoluteValue: number = this.__relativeToAbsolute(relativeValue);
391
+ // console.log("click", "relativeValue", relativeValue, "absoluteValue", absoluteValue);
392
+ // Check if click position (ratio) is far enough away from any slider
393
+ const [leftSliderIndex, closestSliderValue] = _self.__locateClosestSliderValue(absoluteValue);
394
+ const diff: number = Math.abs(closestSliderValue - absoluteValue);
395
+ if (diff >= maxDifference) {
396
+ // console.log("Add slider here");
397
+ _self.__addSliderAt(absoluteValue, leftSliderIndex);
398
+ } else {
399
+ // console.debug("Don't add slider here.");
400
+ }
401
+ // Finally clear mousedown-position
402
+ _self.__mouseDownPosition = null;
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Find that slider (index) that's value is closest to the given absolute value. The function will return
408
+ * the closest value and the left index, indicating the containing interval index.
409
+ *
410
+ * @param {number} absoluteValue - The value to look for.
411
+ * @returns {[number,number]} A pair of left slider index and closest value.
412
+ */
413
+ private __locateClosestSliderValue(absoluteValue: number): [number, number] {
414
+ // As the colorGradient always reflects the slider values we can just ust the color gradient itself to search.
415
+ const relativeValue: number = this.__absoluteToRelative(absoluteValue);
416
+ const colorGradientEntry: [number, ColorGradientItem] = this.colorGradient.locateClosestRatio(relativeValue);
417
+ return [colorGradientEntry[0], this.__relativeToAbsolute(colorGradientEntry[1].ratio)];
418
+ }
419
+
420
+ /**
421
+ * Convert the click event to the relative x value in [0..1].
422
+ *
423
+ * @param {MouseEvent} evt - The mouse event.
424
+ * @returns {number} The relative x value.
425
+ */
426
+ private __clickEventToRelativeValue(evt: MouseEvent): number {
427
+ const target: HTMLDivElement = evt.target as HTMLDivElement;
428
+ const rect: DOMRect = target.getBoundingClientRect();
429
+ const x: number = evt.clientX - rect.left; //x position within the element.
430
+ const width: number = rect.width; // target.clientWidth;
431
+ const relativeValue: number = x / width;
432
+ // console.log("width", width, "x", x, "relativeValue", relativeValue);
433
+ return relativeValue;
434
+ }
435
+
436
+ /**
437
+ * Adds a slider at the given interval index.
438
+ *
439
+ * @param {number} absoluteValue - The absolute new slider value.
440
+ * @param {number} leftSliderIndex - The new slider's position (interval index).
441
+ */
442
+ private __addSliderAt(absoluteValue: number, leftSliderIndex: number) {
443
+ // console.log("__addSliderAt", "absoluteValue", absoluteValue, "leftSliderIndex", leftSliderIndex);
444
+ const leftSlider: HTMLInputElement = this._sliderElementRefs[leftSliderIndex].current;
445
+ // const colorAtPosition = this.__getSliderColorAt(relativeValue);
446
+ const newColor: Color = this.__getSliderColorAt(absoluteValue);
447
+ const newSliderIndex: number = leftSliderIndex + 1;
448
+ const _newSlider: JsxElement = this.__createColorRangeInput(
449
+ newSliderIndex,
450
+ this.sliderMin,
451
+ this.sliderMax,
452
+ absoluteValue,
453
+ newColor // initialColor: string
454
+ );
455
+ const sliderRef = this._sliderElementRefs[newSliderIndex];
456
+ leftSlider.after(sliderRef.current);
457
+ sliderRef.current.dataset.colorValue = newColor.cssRGB();
458
+ sliderRef.current.dataset.colorValueHEX = newColor.cssRGB();
459
+ // No visible change, but let's reflect this in the output gradient anyway
460
+ this.__updateBackgroundGradient();
461
+ // Highlight the newly added range slider
462
+ this.__updateColorIndicator(newSliderIndex);
463
+ this.__fireChangeEvent();
464
+ }
465
+
466
+ /**
467
+ * Get the slider color at the given absolute value. That value must be inside the [MIN_VALUE, MAX_VALUE] interval.
468
+ * @param absoluteValue
469
+ * @returns
470
+ */
471
+ private __getSliderColorAt(absoluteValue: number): Color {
472
+ // console.log("__getSliderColorAt", "absoluteValue", absoluteValue);
473
+ // Locate interval
474
+ const leftIndex: number = this.__locateIntervalAt(absoluteValue);
475
+ const leftSliderValue: number = this.__getSliderValue(leftIndex, NaN);
476
+ const rightSliderValue: number = this.__getSliderValue(leftIndex + 1, NaN);
477
+ if (Number.isNaN(leftSliderValue) || Number.isNaN(rightSliderValue)) {
478
+ console.warn(
479
+ `[Warn] Failed to determine left/right slider values at indices ${leftIndex} or ${rightSliderValue}. Cannot proceed for absolute value ${absoluteValue}.`
480
+ );
481
+ return null;
482
+ }
483
+ const leftColorString: string = this.__getSliderColorString(leftIndex, null);
484
+ const rightColorString: string = this.__getSliderColorString(leftIndex + 1, null);
485
+ if (!leftColorString || !rightColorString) {
486
+ console.warn(
487
+ `[Warn] Failed to determine left/right color string values at indices ${leftIndex} or ${rightSliderValue}. Cannot proceed for absolute value ${absoluteValue}.`
488
+ );
489
+ return null;
490
+ }
491
+ const positionInsideInterval: number = (absoluteValue - leftSliderValue) / (rightSliderValue - leftSliderValue);
492
+ // console.log("leftColorString", leftColorString, "rightColorString", rightColorString);
493
+ const leftColorObject: Color = Color.parse(leftColorString);
494
+ const rightColorObject: Color = Color.parse(rightColorString);
495
+ const newColor: Color = leftColorObject.interpolate(rightColorObject, positionInsideInterval);
496
+ return newColor;
497
+ }
498
+
499
+ /**
500
+ * Locate the slider interval that contains the given (absolute) slider value. The given value must be
501
+ * somewhere between MIN_VALUE and MAX_VALUE (usually between 0 and 100 in the default configuraion.).
502
+ *
503
+ * @param {number} absoluteValue - The absolute value to search for.
504
+ * @returns {number} The left slider inder the containing interval is starting with – or -1 if out of bounds.
505
+ */
506
+ private __locateIntervalAt(absoluteValue: number): number {
507
+ for (var i = 0; i + 1 < this._sliderElementRefs.length; i++) {
508
+ if (
509
+ this.__getSliderValue(i, this.sliderMin) <= absoluteValue &&
510
+ absoluteValue < this.__getSliderValue(i + 1, this.sliderMax)
511
+ ) {
512
+ return i;
513
+ }
514
+ }
515
+ return -1;
516
+ }
517
+
518
+ /**
519
+ * Converts a relative value in [0..1] to [min..max].
520
+ * @param relativeValue
521
+ */
522
+ private __relativeToAbsolute(relativeValue: number): number {
523
+ return this.sliderMin + (this.sliderMax - this.sliderMin) * relativeValue;
524
+ }
525
+
526
+ /**
527
+ * Converts a relative value in [0..1] to [min..max].
528
+ * @param relativeValue
529
+ */
530
+ private __absoluteToRelative(absolute: number): number {
531
+ return (absolute - this.sliderMin) / (this.sliderMax - this.sliderMin);
532
+ }
533
+
534
+ /**
535
+ * Get the value of the n-th rangel slider.
536
+ *
537
+ * @param {number} sliderIndex
538
+ * @param {number} fallback
539
+ * @returns
540
+ */
541
+ private __getSliderValue(sliderIndex: number, fallback: number): number {
542
+ if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {
543
+ return fallback;
544
+ }
545
+ return Number.parseFloat(this._sliderElementRefs[sliderIndex].current.value);
546
+ }
547
+
548
+ /**
549
+ * Get all current slider values as an array.
550
+ * @returns
551
+ */
552
+ private __getAllSliderValues(): Array<number> {
553
+ return this._sliderElementRefs.map((ref, index: number) => this.__getSliderValue(index, NaN));
554
+ }
555
+
556
+ /**
557
+ * Updates the container's background to display the configured color gradient.
558
+ *
559
+ * @private
560
+ */
561
+ private __updateBackgroundGradient() {
562
+ // const colorGradient = this.getColorGradient();
563
+ this.colorGradient = new ColorGradient(
564
+ this.__getAllSliderValues().map((sliderValue: number, sliderIndex: number) => ({
565
+ color: this.__getSliderColor(sliderIndex, null),
566
+ ratio: this.__absoluteToRelative(sliderValue)
567
+ })),
568
+ this.colorGradient.angle
569
+ );
570
+ this.containerRef.current.style["background"] = this.colorGradient.toColorGradientString();
571
+ }
572
+
573
+ /**
574
+ * After changes this function updates the color indicator button.
575
+ *
576
+ * @param {number} rangeSliderIndex - The new active slider index.
577
+ */
578
+ private __updateColorIndicator(rangeSliderIndex: number) {
579
+ const colorValue = this.__getSliderColorHEXString(rangeSliderIndex, "#808080");
580
+ const ratio = this.__getSliderPercentage(rangeSliderIndex);
581
+
582
+ // Set left offset of color input container
583
+ this.colorInputContainerRef.current.style["left"] = `calc( ${ratio * 100}% + ${
584
+ (1.0 - ratio) * this.css_indicatorWidth_num * 0.5
585
+ }em - ${ratio * this.css_indicatorWidth_num * 0.5}em)`;
586
+
587
+ // Also set offset of colot input element (safari will open the native color dialog at this position)
588
+ this.colorInputRef.current.style["left"] = `calc( ${ratio * 100}% + ${
589
+ (1.0 - ratio) * this.css_indicatorWidth_num * 0.5
590
+ }em - ${ratio * this.css_indicatorWidth_num * 0.5}em)`;
591
+ this.colorIndicatorColorButtonRef.current.style["background-color"] = colorValue;
592
+ this.colorInputRef.current.value = colorValue;
593
+ // console.log("Setting new color value", this.colorInputRef.current.value, colorValue);
594
+ this.colorInputRef.current.dataset.activeSliderIndex = `${rangeSliderIndex}`;
595
+
596
+ if (rangeSliderIndex <= 0 || rangeSliderIndex + 1 >= this._sliderElementRefs.length) {
597
+ this.colorIndicatorRemoveButtonRef.current.style["visibility"] = "hidden";
598
+ } else {
599
+ this.colorIndicatorRemoveButtonRef.current.style["visibility"] = "visible";
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Get a color gradient CSS value string from the current editor settings.
605
+ *
606
+ * @instance
607
+ * @memberof ColorGradientPicker
608
+ * @returns {ColorGradient}
609
+ */
610
+ public getColorGradient(): ColorGradient {
611
+ return this.colorGradient;
612
+ }
613
+
614
+ /**
615
+ * Get the configured color value of the n-th rangel slider.
616
+ *
617
+ * @param {number} sliderIndex
618
+ * @param {string} fallback
619
+ * @returns
620
+ */
621
+ private __getSliderColorString(sliderIndex: number, fallback: string): string {
622
+ if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {
623
+ return fallback;
624
+ }
625
+ const colorValue = this._sliderElementRefs[sliderIndex].current.dataset.colorValue;
626
+ return colorValue ? colorValue : fallback;
627
+ }
628
+
629
+ /**
630
+ * Get the configured color value of the n-th rangel slider.
631
+ *
632
+ * @param {number} sliderIndex
633
+ * @param {string} fallback
634
+ * @returns
635
+ */
636
+ private __getSliderColorHEXString(sliderIndex: number, fallback: string): string {
637
+ if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {
638
+ return fallback;
639
+ }
640
+ const colorValue = this._sliderElementRefs[sliderIndex].current.dataset.colorValueHEX;
641
+ return colorValue ? colorValue : fallback;
642
+ }
643
+
644
+ /**
645
+ * Get get color of this gradient picker at the given slider index.
646
+ *
647
+ * @param {number} sliderIndex - The index to get the slider color from. Something between 0 and _sliderElementRefs.length.
648
+ * @param {Color} fallback
649
+ * @returns
650
+ */
651
+ private __getSliderColor(sliderIndex: number, fallback: Color): Color {
652
+ if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {
653
+ return fallback;
654
+ }
655
+ const colorValueString = this._sliderElementRefs[sliderIndex].current.dataset["colorValue"];
656
+ const colorValue = Color.parse(colorValueString);
657
+ return colorValue ? colorValue : fallback;
658
+ }
659
+
660
+ /**
661
+ * Get the slider's value in a mapped range of 0.0 ... 1.0.
662
+ *
663
+ * @param sliderIndex
664
+ * @returns
665
+ */
666
+ private __getSliderPercentage(sliderIndex): number {
667
+ const sliderValue: number = this.__getSliderValue(sliderIndex, 0.0);
668
+ const percentage: number = (this.sliderMin + sliderValue) / (this.sliderMax - this.sliderMin);
669
+ return percentage;
670
+ }
671
+
672
+ /**
673
+ * Init the container contents.
674
+ *
675
+ * @private
676
+ */
677
+ private _render(): HTMLElement {
678
+ const _self = this;
679
+ // console.log("Rendering ...", NoReact);
680
+ this._sliderElementRefs = [];
681
+ this.colorIndicatorColorButtonRef = NoReact.useRef<HTMLButtonElement>();
682
+ this.colorIndicatorRemoveButtonRef = NoReact.useRef<HTMLButtonElement>();
683
+ this.colorInputRef = NoReact.useRef<HTMLInputElement>();
684
+ this.colorInputContainerRef = NoReact.useRef<HTMLInputElement>();
685
+ this.containerRef = NoReact.useRef<HTMLDivElement>();
686
+
687
+ /**
688
+ * This helper method is called when the tiny color button below the active slider is clicked. The method
689
+ * triggers the colorInput dialog to be triggered.
690
+ *
691
+ * @param {Event} evt
692
+ */
693
+ const handleIndicatorButtonClick = (evt: Event) => {
694
+ evt.preventDefault(); // Prevent other inputs to react to this event.
695
+ evt.stopPropagation();
696
+ // But fake a click on the input element
697
+ // console.log("Current selected color: " + _self.colorInputRef.current.value);
698
+ _self.colorInputRef.current.click();
699
+ };
700
+
701
+ /**
702
+ * This helper method is called when the remove-color button is clicked. It removes the
703
+ * currently active color slider – if possible (leftmost and rightmost slider cannot be removed).
704
+ * @param evt
705
+ */
706
+ const handleRemoveColorButtonClick = (evt: Event) => {
707
+ evt.preventDefault(); // Prevent other inputs to react to this event.
708
+ evt.stopPropagation();
709
+ _self.__handleRemoveColor();
710
+ };
711
+
712
+ return (
713
+ <div
714
+ id={this.elementID}
715
+ style={{
716
+ d: "flex",
717
+ fd: "column",
718
+ w: "100%",
719
+ h: this.css_containerHeight,
720
+ pos: "relative",
721
+ mb: this.isMobileMode ? "5em" : "3em"
722
+ }}
723
+ ref={this.containerRef}
724
+ onMouseDown={this.__containerMouseDownHandler()}
725
+ onClick={this.__containerClickHandler()}
726
+ >
727
+ {/* For each color gradient value create a range slider. */}
728
+ {this.colorGradient.values.map((colorGradientItem: ColorGradientItem, index: number) => {
729
+ const initialValue: number = _self.__relativeToAbsolute(colorGradientItem.ratio);
730
+ return this.__createColorRangeInput(index, this.sliderMin, this.sliderMax, initialValue, colorGradientItem.color);
731
+ })}
732
+ <div style={{ w: "100%" }}>
733
+ <input
734
+ id={`color-indicator-input-${this.baseID}`}
735
+ type="color"
736
+ style={{ v: "hidden", pos: "absolute", l: 0 }}
737
+ // data-active-slider-index=""
738
+ ref={this.colorInputRef}
739
+ onInput={this.__colorChangeHandler()}
740
+ />
741
+ <div
742
+ ref={this.colorInputContainerRef}
743
+ style={{
744
+ pos: "absolute",
745
+ b: "0px",
746
+ l: "0%",
747
+ d: "flex",
748
+ fd: "column",
749
+ transform: "translate(0%, 100%)"
750
+ }}
751
+ >
752
+ <button
753
+ id={`color-indicator-button-${this.baseID}`}
754
+ style={{
755
+ backgroundColor: "grey",
756
+ borderRadius: "10%",
757
+ border: "1px solid grey",
758
+ w: this.css_indicatorWidth, // "1em",
759
+ h: this.css_indicatorHeight, // "1em",
760
+ transform: "translate(-50%, 0%)"
761
+ }}
762
+ onClick={handleIndicatorButtonClick}
763
+ ref={this.colorIndicatorColorButtonRef}
764
+ ></button>
765
+ <button
766
+ id={`color-remove-button-${this.baseID}`}
767
+ className="color-remove-button"
768
+ style={{
769
+ backgroundColor: "grey",
770
+ borderRadius: "10%",
771
+ border: "1px solid grey",
772
+ w: this.css_indicatorWidth, // "1em",
773
+ h: this.css_indicatorHeight, // "1em",
774
+ transform: "translate(-50%, 50%)",
775
+ lineHeight: "0.5em",
776
+ p: 0
777
+ }}
778
+ onClick={handleRemoveColorButtonClick}
779
+ ref={this.colorIndicatorRemoveButtonRef}
780
+ >
781
+ <span style={{ fontSize: this.isMobileMode ? "1.0em" : "0.5em" }}>🗑</span>
782
+ </button>
783
+ </div>
784
+ </div>
785
+ </div>
786
+ );
787
+ } // END function render()
788
+
789
+ /**
790
+ * Adds custom styles (global STYLE tag).
791
+ *
792
+ * @private
793
+ */
794
+ private __createCustomStylesElement = () => {
795
+ // Thanks to Ana Tudor
796
+ // https://css-tricks.com/multi-thumb-sliders-particular-two-thumb-case/
797
+ return (
798
+ <style>{`
799
+ #${this.elementID} {
800
+ margin-top: 1em;
801
+ }
802
+
803
+ #${this.elementID} input[type='range'] {
804
+
805
+ -webkit-appearance: none;
806
+
807
+ grid-column: 1;
808
+ grid-row: 2;
809
+
810
+ /* same as before */
811
+ background: none; /* get rid of white Chrome background */
812
+ color: #000;
813
+ font: inherit; /* fix too small font-size in both Chrome & Firefox */
814
+ margin: 0;
815
+ pointer-events: none; /* let clicks pass through */
816
+ }
817
+
818
+ #${this.elementID} input[type='range']::-webkit-slider-runnable-track {
819
+ -webkit-appearance: none;
820
+
821
+ background: none; /* get rid of Firefox track background */
822
+ height: 100%;
823
+ width: 100%;
824
+
825
+ pointer-events: none;
826
+ }
827
+
828
+ #${this.elementID} input[type='range']::-webkit-slider-thumb {
829
+ -webkit-appearance: none;
830
+ background: currentcolor;
831
+ border: none; /* get rid of Firefox thumb border */
832
+ border-radius: 6px; /* get rid of Firefox corner rounding */
833
+ pointer-events: auto; /* catch clicks */
834
+ width: ${this.css_thumbWidth};
835
+ height: ${this.css_thumbHeight};
836
+ }
837
+
838
+ #${this.elementID} input[type='range']:focus::-webkit-slider-thumb {
839
+ border: 2px solid white;
840
+ }
841
+
842
+ #${this.elementID} input[type='range']::-moz-range-track {
843
+ -webkit-appearance: none;
844
+ background: none; /* get rid of Firefox track background */
845
+ height: 100%;
846
+ width: 100%;
847
+ pointer-events: none;
848
+ }
849
+
850
+ #${this.elementID} input[type='range']::-moz-range-thumb {
851
+ /* -webkit-appearance: none; */
852
+ background: currentcolor;
853
+ border: none; /* get rid of Firefox thumb border */
854
+ border-radius: 6px; /* get rid of Firefox corner rounding */
855
+ pointer-events: auto; /* catch clicks */
856
+ width: ${this.css_thumbWidth};
857
+ height: ${this.css_thumbHeight};
858
+ }
859
+
860
+ #${this.elementID} input[type='range']:focus::-moz-range-thumb {
861
+ border: 2px solid white;
862
+ }
863
+
864
+ #${this.elementID} input[type='range'] {
865
+ /* same as before */
866
+ z-index: 1;
867
+ }
868
+
869
+ #${this.elementID} input[type='range']:focus {
870
+ z-index: 2;
871
+ /* outline: dotted 1px orange; */
872
+ color: darkorange;
873
+ }
874
+ `}</style>
875
+ );
876
+ };
877
+ }