dash-core-components 3.2.0 → 4.0.0-rc0

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 (50) hide show
  1. package/dash_core_components/async-datepicker.js +1 -1
  2. package/dash_core_components/async-datepicker.js.map +1 -1
  3. package/dash_core_components/async-dropdown.js +1 -1
  4. package/dash_core_components/async-dropdown.js.map +1 -1
  5. package/dash_core_components/async-highlight.js +1 -1
  6. package/dash_core_components/async-highlight.js.map +1 -1
  7. package/dash_core_components/async-markdown.js +1 -1
  8. package/dash_core_components/async-markdown.js.map +1 -1
  9. package/dash_core_components/async-slider.js +1 -1
  10. package/dash_core_components/async-slider.js.map +1 -1
  11. package/dash_core_components/dash_core_components-shared.js +1 -1
  12. package/dash_core_components/dash_core_components-shared.js.map +1 -1
  13. package/dash_core_components/dash_core_components.js +1 -1
  14. package/dash_core_components/dash_core_components.js.map +1 -1
  15. package/dash_core_components/plotly.min.js +8 -0
  16. package/dash_core_components/proptypes.js +81 -0
  17. package/lib/components/Dropdown.react.js.old +228 -0
  18. package/lib/components/Input.react.js.old +507 -0
  19. package/lib/components/Input.tsx +543 -0
  20. package/lib/components/RangeSlider.tsx +39 -0
  21. package/lib/components/Slider.react.js.old +214 -0
  22. package/lib/components/Slider.tsx +81 -0
  23. package/lib/components/css/dcc.css +13 -0
  24. package/lib/components/css/input.css +116 -2
  25. package/lib/components/css/react-select@1.0.0-rc.3.min.css +1 -1
  26. package/lib/components/css/sliders.css +198 -4
  27. package/lib/fragments/RangeSlider.tsx +412 -0
  28. package/lib/fragments/Slider.tsx.old +364 -0
  29. package/lib/index.ts +58 -0
  30. package/lib/types.ts +331 -0
  31. package/lib/utils/LazyLoader/rangeSlider.ts +2 -0
  32. package/lib/utils/LazyLoader/slider.ts +2 -0
  33. package/lib/utils/_LoadingElement.tsx +36 -0
  34. package/lib/utils/computeSliderMarkers.ts +302 -0
  35. package/lib/utils/formatSliderTooltip.ts +20 -0
  36. package/lib/utils/sliderRendering.tsx +144 -0
  37. package/lib/utils/sliderSnapToMark.ts +17 -0
  38. package/lib/utils/sliderTooltip.tsx +65 -0
  39. package/package.json +22 -4
  40. package/lib/components/Input.react.js +0 -403
  41. package/lib/components/RangeSlider.react.js +0 -194
  42. package/lib/components/Slider.react.js +0 -179
  43. package/lib/fragments/RangeSlider.react.js +0 -143
  44. package/lib/fragments/Slider.react.js +0 -159
  45. package/lib/index.js +0 -183
  46. package/lib/utils/LazyLoader/rangeSlider.js +0 -8
  47. package/lib/utils/LazyLoader/slider.js +0 -8
  48. package/lib/utils/computeSliderMarkers.js +0 -153
  49. package/lib/utils/computeSliderStyle.js +0 -26
  50. package/lib/utils/formatSliderTooltip.js +0 -19
package/lib/types.ts ADDED
@@ -0,0 +1,331 @@
1
+ export enum PersistenceTypes {
2
+ 'local' = 'local',
3
+ 'session' = 'session',
4
+ 'memory' = 'memory',
5
+ }
6
+
7
+ export enum PersistedProps {
8
+ 'value' = 'value',
9
+ }
10
+
11
+ export type SliderMarks = {
12
+ [key: number]: string | {label: string; style?: React.CSSProperties};
13
+ };
14
+
15
+ export type SliderTooltip = {
16
+ /**
17
+ * Determines whether tooltips should always be visible
18
+ * (as opposed to the default, visible on hover)
19
+ */
20
+ always_visible?: boolean;
21
+
22
+ /**
23
+ * Determines the placement of tooltips
24
+ * See https://github.com/react-component/tooltip#api
25
+ * top/bottom{*} sets the _origin_ of the tooltip, so e.g. `topLeft`
26
+ * will in reality appear to be on the top right of the handle
27
+ */
28
+ placement?:
29
+ | 'left'
30
+ | 'right'
31
+ | 'top'
32
+ | 'bottom'
33
+ | 'topLeft'
34
+ | 'topRight'
35
+ | 'bottomLeft'
36
+ | 'bottomRight';
37
+
38
+ /**
39
+ * Template string to display the tooltip in.
40
+ * Must contain `{value}`, which will be replaced with either
41
+ * the default string representation of the value or the result of the
42
+ * transform function if there is one.
43
+ */
44
+ template?: string;
45
+
46
+ /**
47
+ * Custom style for the tooltip.
48
+ */
49
+ style?: React.CSSProperties;
50
+
51
+ /**
52
+ * Reference to a function in the `window.dccFunctions` namespace.
53
+ * This can be added in a script in the asset folder.
54
+ *
55
+ * For example, in `assets/tooltip.js`:
56
+ * ```
57
+ * window.dccFunctions = window.dccFunctions || {};
58
+ * window.dccFunctions.multByTen = function(value) {
59
+ * return value * 10;
60
+ * }
61
+ * ```
62
+ * Then in the component `tooltip={'transform': 'multByTen'}`
63
+ */
64
+ transform?: string;
65
+ };
66
+
67
+ export interface SliderProps {
68
+ /**
69
+ * Minimum allowed value of the slider
70
+ */
71
+ min?: number;
72
+
73
+ /**
74
+ * Maximum allowed value of the slider
75
+ */
76
+ max?: number;
77
+
78
+ /**
79
+ * Value by which increments or decrements are made
80
+ */
81
+ step?: number | null;
82
+
83
+ /**
84
+ * Marks on the slider.
85
+ * The key determines the position (a number),
86
+ * and the value determines what will show.
87
+ * If you want to set the style of a specific mark point,
88
+ * the value should be an object which
89
+ * contains style and label properties.
90
+ */
91
+ marks?: SliderMarks | null;
92
+
93
+ /**
94
+ * The value of the input
95
+ */
96
+ value?: number | null;
97
+
98
+ /**
99
+ * The value of the input during a drag
100
+ */
101
+ drag_value?: number;
102
+
103
+ /**
104
+ * If true, the handles can't be moved.
105
+ */
106
+ disabled?: boolean;
107
+
108
+ /**
109
+ * When the step value is greater than 1,
110
+ * you can set the dots to true if you want to
111
+ * render the slider with dots.
112
+ */
113
+ dots?: boolean;
114
+
115
+ /**
116
+ * If the value is true, it means a continuous
117
+ * value is included. Otherwise, it is an independent value.
118
+ */
119
+ included?: boolean;
120
+
121
+ /**
122
+ * Configuration for tooltips describing the current slider value
123
+ */
124
+ tooltip?: SliderTooltip;
125
+
126
+ /**
127
+ * Determines when the component should update its `value`
128
+ * property. If `mouseup` (the default) then the slider
129
+ * will only trigger its value when the user has finished
130
+ * dragging the slider. If `drag`, then the slider will
131
+ * update its value continuously as it is being dragged.
132
+ * If you want different actions during and after drag,
133
+ * leave `updatemode` as `mouseup` and use `drag_value`
134
+ * for the continuously updating value.
135
+ */
136
+ updatemode?: 'mouseup' | 'drag';
137
+
138
+ /**
139
+ * If true, the slider will be vertical
140
+ */
141
+ vertical?: boolean;
142
+
143
+ /**
144
+ * The height, in px, of the slider if it is vertical.
145
+ */
146
+ verticalHeight?: number;
147
+
148
+ /**
149
+ * Additional CSS class for the root DOM node
150
+ */
151
+ className?: string;
152
+
153
+ /**
154
+ * The ID of this component, used to identify dash components
155
+ * in callbacks. The ID needs to be unique across all of the
156
+ * components in an app.
157
+ */
158
+ id?: string;
159
+
160
+ /**
161
+ * Dash-assigned callback that gets fired when the value or drag_value changes.
162
+ */
163
+ setProps: (props: Partial<SliderProps>) => void;
164
+
165
+ /**
166
+ * Used to allow user interactions in this component to be persisted when
167
+ * the component - or the page - is refreshed. If `persisted` is truthy and
168
+ * hasn't changed from its previous value, a `value` that the user has
169
+ * changed while using the app will keep that change, as long as
170
+ * the new `value` also matches what was given originally.
171
+ * Used in conjunction with `persistence_type`.
172
+ */
173
+ persistence?: boolean | string | number;
174
+
175
+ /**
176
+ * Properties whose user interactions will persist after refreshing the
177
+ * component or the page. Since only `value` is allowed this prop can
178
+ * normally be ignored.
179
+ */
180
+ persisted_props?: PersistedProps[];
181
+
182
+ /**
183
+ * Where persisted user changes will be stored:
184
+ * memory: only kept in memory, reset on page refresh.
185
+ * local: window.localStorage, data is kept after the browser quit.
186
+ * session: window.sessionStorage, data is cleared once the browser quit.
187
+ */
188
+ persistence_type?: PersistenceTypes;
189
+ }
190
+
191
+ export interface RangeSliderProps {
192
+ /**
193
+ * Minimum allowed value of the slider
194
+ */
195
+ min?: number;
196
+
197
+ /**
198
+ * Maximum allowed value of the slider
199
+ */
200
+ max?: number;
201
+
202
+ /**
203
+ * Value by which increments or decrements are made
204
+ */
205
+ step?: number | null;
206
+
207
+ /**
208
+ * Marks on the slider.
209
+ * The key determines the position (a number),
210
+ * and the value determines what will show.
211
+ * If you want to set the style of a specific mark point,
212
+ * the value should be an object which
213
+ * contains style and label properties.
214
+ */
215
+ marks?: SliderMarks | null;
216
+
217
+ /**
218
+ * The value of the input
219
+ */
220
+ value?: number[] | null;
221
+
222
+ /**
223
+ * The value of the input during a drag
224
+ */
225
+ drag_value?: number[];
226
+
227
+ /**
228
+ * allowCross could be set as true to allow those handles to cross.
229
+ */
230
+ allowCross?: boolean;
231
+
232
+ /**
233
+ * pushable could be set as true to allow pushing of
234
+ * surrounding handles when moving an handle.
235
+ * When set to a number, the number will be the
236
+ * minimum ensured distance between handles.
237
+ */
238
+ pushable?: boolean | number;
239
+
240
+ /**
241
+ * If true, the handles can't be moved.
242
+ */
243
+ disabled?: boolean;
244
+
245
+ /**
246
+ * Determine how many ranges to render, and multiple handles
247
+ * will be rendered (number + 1).
248
+ */
249
+ count?: number;
250
+
251
+ /**
252
+ * When the step value is greater than 1,
253
+ * you can set the dots to true if you want to
254
+ * render the slider with dots.
255
+ */
256
+ dots?: boolean;
257
+
258
+ /**
259
+ * If the value is true, it means a continuous
260
+ * value is included. Otherwise, it is an independent value.
261
+ */
262
+ included?: boolean;
263
+
264
+ /**
265
+ * Configuration for tooltips describing the current slider values
266
+ */
267
+ tooltip?: SliderTooltip;
268
+
269
+ /**
270
+ * Determines when the component should update its `value`
271
+ * property. If `mouseup` (the default) then the slider
272
+ * will only trigger its value when the user has finished
273
+ * dragging the slider. If `drag`, then the slider will
274
+ * update its value continuously as it is being dragged.
275
+ * Note that for the latter case, the `drag_value`
276
+ * property could be used instead.
277
+ */
278
+ updatemode?: 'mouseup' | 'drag';
279
+
280
+ /**
281
+ * If true, the slider will be vertical
282
+ */
283
+ vertical?: boolean;
284
+
285
+ /**
286
+ * The height, in px, of the slider if it is vertical.
287
+ */
288
+ verticalHeight?: number;
289
+
290
+ /**
291
+ * Additional CSS class for the root DOM node
292
+ */
293
+ className?: string;
294
+
295
+ /**
296
+ * The ID of this component, used to identify dash components
297
+ * in callbacks. The ID needs to be unique across all of the
298
+ * components in an app.
299
+ */
300
+ id?: string;
301
+
302
+ /**
303
+ * Dash-assigned callback that gets fired when the value or drag_value changes.
304
+ */
305
+ setProps: (props: Partial<RangeSliderProps>) => void;
306
+
307
+ /**
308
+ * Used to allow user interactions in this component to be persisted when
309
+ * the component - or the page - is refreshed. If `persisted` is truthy and
310
+ * hasn't changed from its previous value, a `value` that the user has
311
+ * changed while using the app will keep that change, as long as
312
+ * the new `value` also matches what was given originally.
313
+ * Used in conjunction with `persistence_type`.
314
+ */
315
+ persistence?: boolean | string | number;
316
+
317
+ /**
318
+ * Properties whose user interactions will persist after refreshing the
319
+ * component or the page. Since only `value` is allowed this prop can
320
+ * normally be ignored.
321
+ */
322
+ persisted_props?: PersistedProps[];
323
+
324
+ /**
325
+ * Where persisted user changes will be stored:
326
+ * memory: only kept in memory, reset on page refresh.
327
+ * local: window.localStorage, data is kept after the browser quit.
328
+ * session: window.sessionStorage, data is cleared once the browser quit.
329
+ */
330
+ persistence_type?: PersistenceTypes;
331
+ }
@@ -0,0 +1,2 @@
1
+ export default () =>
2
+ import(/* webpackChunkName: "slider" */ '../../fragments/RangeSlider');
@@ -0,0 +1,2 @@
1
+ export default () =>
2
+ import(/* webpackChunkName: "slider" */ '../../fragments/Slider');
@@ -0,0 +1,36 @@
1
+ import React from 'react';
2
+
3
+ declare global {
4
+ interface Window {
5
+ dash_component_api: {
6
+ useDashContext: () => {
7
+ useLoading: () => boolean;
8
+ };
9
+ };
10
+ }
11
+ }
12
+
13
+ interface LoadingElementProps {
14
+ children: (props: Record<string, unknown>) => React.ReactElement;
15
+ }
16
+
17
+ /**
18
+ * The loading element is used to add `data-dash-is-loading` attribute
19
+ * on html elements. This is used to customize CSS when a component is
20
+ * loading.
21
+ *
22
+ * See: https://dash.plotly.com/loading-states#check-loading-states-from-components
23
+ */
24
+ function LoadingElement({children}: LoadingElementProps) {
25
+ const ctx = window.dash_component_api.useDashContext();
26
+ const loading = ctx.useLoading();
27
+
28
+ const additionalProps: Record<string, unknown> = {};
29
+ if (loading) {
30
+ additionalProps['data-dash-is-loading'] = true;
31
+ }
32
+
33
+ return children(additionalProps);
34
+ }
35
+
36
+ export default LoadingElement;
@@ -0,0 +1,302 @@
1
+ import {pickBy, isEmpty, isNil} from 'ramda';
2
+ import {formatPrefix} from 'd3-format';
3
+ import {SliderMarks} from '../types';
4
+
5
+ /**
6
+ * Truncate marks if they are out of Slider interval
7
+ */
8
+ const truncateMarks = (
9
+ min: number,
10
+ max: number,
11
+ marks: SliderMarks
12
+ ): SliderMarks => pickBy((k, mark) => mark >= min && mark <= max, marks);
13
+
14
+ const truncateNumber = (num: number) => {
15
+ const match = num.toString().match(/^-?\d+(?:\.\d{0,0})?/);
16
+ return match ? parseInt(match[0], 10) : 0;
17
+ };
18
+
19
+ const decimalCount = (d: number) =>
20
+ String(d).split('.').length > 1 ? String(d).split('.')[1].length : 0;
21
+ const alignIntValue = (v: number, d: number) =>
22
+ d < 10
23
+ ? v
24
+ : parseInt((truncateNumber(v / d) * d).toFixed(decimalCount(d)), 10);
25
+ const alignDecimalValue = (v: number, d: number) =>
26
+ d < 10
27
+ ? parseFloat(v.toFixed(decimalCount(d)))
28
+ : parseFloat(
29
+ (parseFloat((v / d).toFixed(0)) * d).toFixed(decimalCount(d))
30
+ );
31
+
32
+ const alignValue = (v: number, d: number) =>
33
+ decimalCount(d) < 1 ? alignIntValue(v, d) : alignDecimalValue(v, d);
34
+
35
+ const estimateBestSteps = (
36
+ minValue: number,
37
+ maxValue: number,
38
+ stepValue: number,
39
+ sliderWidth?: number | null
40
+ ) => {
41
+ // Base desired count for 330px slider with 0-100 scale (10 marks = 11 total including endpoints)
42
+ let targetMarkCount = 11; // Default baseline
43
+
44
+ // Scale mark density based on slider width
45
+ if (sliderWidth) {
46
+ const baselineWidth = 330;
47
+ const baselineMarkCount = 11; // 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
48
+
49
+ // Calculate density multiplier based on width
50
+ const widthMultiplier = sliderWidth / baselineWidth;
51
+
52
+ // Target mark count scales with width but maintains consistent density
53
+ // The range adjustment should be removed - we want consistent mark density based on width
54
+ targetMarkCount = Math.round(baselineMarkCount * widthMultiplier);
55
+
56
+ // Ensure reasonable bounds
57
+ const UPPER_BOUND = 50;
58
+ targetMarkCount = Math.max(3, Math.min(targetMarkCount, UPPER_BOUND));
59
+
60
+ // Adjust density based on maximum character width of mark labels
61
+ // Estimate the maximum characters in any mark label
62
+ const maxValueChars = Math.max(
63
+ String(minValue).length,
64
+ String(maxValue).length,
65
+ String(Math.abs(minValue)).length,
66
+ String(Math.abs(maxValue)).length
67
+ );
68
+
69
+ // Baseline: 3-4 characters (like "100", "250") work well with baseline density
70
+ // For longer labels, reduce density to prevent overlap
71
+ const baselineChars = 3.5;
72
+ if (maxValueChars > baselineChars) {
73
+ const charReductionFactor = baselineChars / maxValueChars;
74
+ targetMarkCount = Math.round(targetMarkCount * charReductionFactor);
75
+ targetMarkCount = Math.max(2, targetMarkCount); // Ensure minimum of 2 marks
76
+ }
77
+ }
78
+
79
+ // Calculate the ideal interval between marks based on target count
80
+ const range = maxValue - minValue;
81
+ let idealInterval = range / (targetMarkCount - 1);
82
+
83
+ // Check if the step value is fractional and adjust density
84
+ if (stepValue % 1 !== 0) {
85
+ // For fractional steps, reduce mark density by half to avoid clutter
86
+ targetMarkCount = Math.max(3, Math.round(targetMarkCount / 2));
87
+ idealInterval = range / (targetMarkCount - 1);
88
+ }
89
+
90
+ // Find the best interval that's a multiple of stepValue
91
+ // Start with multiples of stepValue and find the one closest to idealInterval
92
+ const stepMultipliers = [
93
+ // eslint-disable-next-line no-magic-numbers
94
+ 1, 2, 2.5, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000,
95
+ ];
96
+
97
+ let bestInterval = stepValue;
98
+ let bestDifference = Math.abs(idealInterval - stepValue);
99
+
100
+ for (const multiplier of stepMultipliers) {
101
+ const candidateInterval = stepValue * multiplier;
102
+ const difference = Math.abs(idealInterval - candidateInterval);
103
+
104
+ if (difference < bestDifference) {
105
+ bestInterval = candidateInterval;
106
+ bestDifference = difference;
107
+ }
108
+
109
+ // Stop if we've gone too far beyond the ideal
110
+ if (candidateInterval > idealInterval * 2) {
111
+ break;
112
+ }
113
+ }
114
+
115
+ // All marks must be at valid step positions: minValue + (n * stepValue)
116
+ // Find the first mark after minValue that fits our desired interval
117
+ const stepsInInterval = Math.round(bestInterval / stepValue);
118
+ const actualInterval = stepsInInterval * stepValue;
119
+
120
+ // Find the first mark position that's aligned with our interval
121
+ // This ensures we don't have overlapping marks at narrow widths
122
+ const firstMarkSteps = Math.max(1, stepsInInterval);
123
+ const firstStepAfterMin = minValue + firstMarkSteps * stepValue;
124
+
125
+ return [firstStepAfterMin, actualInterval, stepValue];
126
+ };
127
+
128
+ /**
129
+ * Calculate default step if not defined
130
+ */
131
+ export const calcStep = (min?: number, max?: number, step?: number | null) => {
132
+ if (step) {
133
+ return step;
134
+ }
135
+
136
+ if (isNil(min) || isNil(max)) {
137
+ return 1;
138
+ }
139
+
140
+ const diff = max > min ? max - min : min - max;
141
+
142
+ const v = (Math.abs(diff) + Number.EPSILON) / 100;
143
+ const N = Math.floor(Math.log10(v));
144
+ return [
145
+ Number(Math.pow(10, N)),
146
+ 2 * Math.pow(10, N),
147
+ 5 * Math.pow(10, N),
148
+ ].sort((a, b) => Math.abs(a - v) - Math.abs(b - v))[0];
149
+ };
150
+
151
+ /**
152
+ * Set min and max if they are undefined and marks are defined
153
+ */
154
+ export const setUndefined = (
155
+ min: number | undefined,
156
+ max: number | undefined,
157
+ marks: SliderMarks | undefined | null
158
+ ) => {
159
+ const definedMarks = {min_mark: min ?? 0, max_mark: max ?? 1};
160
+
161
+ if (isNil(marks)) {
162
+ return definedMarks;
163
+ }
164
+
165
+ const marksObject = Object.keys(marks).map(Number);
166
+
167
+ if (isNil(min)) {
168
+ definedMarks.min_mark = Math.min(...marksObject);
169
+ }
170
+
171
+ if (isNil(max)) {
172
+ definedMarks.max_mark = Math.max(...marksObject);
173
+ }
174
+
175
+ return definedMarks;
176
+ };
177
+
178
+ export const applyD3Format = (mark: number, min: number, max: number) => {
179
+ const mu_ten_factor = -3;
180
+ const k_ten_factor = 3;
181
+
182
+ const ten_factor = Math.log10(Math.abs(mark));
183
+ if (
184
+ mark === 0 ||
185
+ (ten_factor > mu_ten_factor && ten_factor < k_ten_factor)
186
+ ) {
187
+ return String(mark);
188
+ }
189
+ const max_min_mean = (Math.abs(max) + Math.abs(min)) / 2;
190
+ const si_formatter = formatPrefix(',.0', max_min_mean);
191
+ return String(si_formatter(mark));
192
+ };
193
+
194
+ export const autoGenerateMarks = (
195
+ min: number,
196
+ max: number,
197
+ step?: number | null,
198
+ sliderWidth?: number | null
199
+ ) => {
200
+ const marks = [];
201
+ // Always use dynamic logic, but pass the provided step as a constraint
202
+ const effectiveStep = step || calcStep(min, max, 0);
203
+ const [start, interval, chosenStep] = estimateBestSteps(
204
+ min,
205
+ max,
206
+ effectiveStep,
207
+ sliderWidth
208
+ );
209
+ let cursor = start;
210
+
211
+ // Apply a safety cap to prevent excessive mark generation while preserving existing behavior
212
+ // Only restrict when marks would be truly excessive (much higher than the existing UPPER_BOUND)
213
+ const MARK_WIDTH_PX = 20; // More generous spacing for width-based calculation
214
+ const FALLBACK_MAX_MARKS = 200; // High fallback to preserve existing behavior when no width
215
+ const ABSOLUTE_MAX_MARKS = 200; // Safety cap against extreme cases
216
+
217
+ const widthBasedMax = sliderWidth
218
+ ? Math.max(10, Math.floor(sliderWidth / MARK_WIDTH_PX))
219
+ : FALLBACK_MAX_MARKS;
220
+
221
+ const maxAutoGeneratedMarks = Math.min(widthBasedMax, ABSOLUTE_MAX_MARKS);
222
+
223
+ // Calculate how many marks would be generated with current interval
224
+ const estimatedMarkCount = Math.floor((max - start) / interval) + 1;
225
+
226
+ // If we would exceed the limit, increase the interval to fit within the limit
227
+ let actualInterval = interval;
228
+ if (estimatedMarkCount > maxAutoGeneratedMarks) {
229
+ // Recalculate interval to fit exactly within the limit
230
+ actualInterval = (max - start) / (maxAutoGeneratedMarks - 1);
231
+ // Round to a reasonable step multiple to keep marks clean
232
+ const stepMultiple = Math.ceil(actualInterval / chosenStep);
233
+ actualInterval = stepMultiple * chosenStep;
234
+ }
235
+
236
+ if ((max - cursor) / actualInterval > 0) {
237
+ do {
238
+ marks.push(alignValue(cursor, chosenStep));
239
+ cursor += actualInterval;
240
+ } while (cursor < max && marks.length < maxAutoGeneratedMarks);
241
+
242
+ // do some cosmetic
243
+ const discardThreshold = 1.5;
244
+ if (
245
+ marks.length >= 2 &&
246
+ max - marks[marks.length - 2] <= interval * discardThreshold
247
+ ) {
248
+ marks.pop();
249
+ }
250
+ }
251
+ const marksObject: SliderMarks = {};
252
+ marks.forEach(mark => {
253
+ marksObject[mark] = applyD3Format(mark, min, max);
254
+ });
255
+ marksObject[min] = applyD3Format(min, min, max);
256
+ marksObject[max] = applyD3Format(max, min, max);
257
+ return marksObject;
258
+ };
259
+
260
+ /**
261
+ * - Auto generate marks if not given,
262
+ * - Not generate anything at all when explicit null is given to marks
263
+ * - Then truncate marks so no out of range marks
264
+ */
265
+ type SanitizeMarksParams = {
266
+ min?: number;
267
+ max?: number;
268
+ marks?: SliderMarks;
269
+ step?: number | null;
270
+ sliderWidth?: number | null;
271
+ };
272
+ export const sanitizeMarks = ({
273
+ min,
274
+ max,
275
+ marks,
276
+ step,
277
+ sliderWidth,
278
+ }: SanitizeMarksParams): SliderMarks => {
279
+ const {min_mark, max_mark} = setUndefined(min, max, marks);
280
+
281
+ const truncated_marks =
282
+ marks && isEmpty(marks) === false
283
+ ? truncateMarks(min_mark, max_mark, marks)
284
+ : marks;
285
+
286
+ if (truncated_marks && isEmpty(truncated_marks) === false) {
287
+ return truncated_marks;
288
+ }
289
+
290
+ return autoGenerateMarks(min_mark, max_mark, step, sliderWidth);
291
+ };
292
+
293
+ /**
294
+ * Calculate default value if not defined
295
+ */
296
+ export const calcValue = (min: number, max: number, value: unknown) => {
297
+ if (value !== undefined) {
298
+ return value;
299
+ }
300
+
301
+ return [min, max];
302
+ };
@@ -0,0 +1,20 @@
1
+ import {replace, path, split, concat, pipe} from 'ramda';
2
+
3
+ export const formatSliderTooltip = (template: string, value: string | number) => {
4
+ return replace('{value}', `${value}`, template);
5
+ };
6
+
7
+ export const transformSliderTooltip = (funcName: string, value: string | number) => {
8
+ type TransformFunc = (value: string | number) => string | number;
9
+ const func = pipe(
10
+ split('.'),
11
+ s => concat(['dccFunctions'], s),
12
+ s => path(s, window)
13
+ )(funcName) as TransformFunc;
14
+ if (!func) {
15
+ throw new Error(
16
+ `Invalid func for slider tooltip transform: ${funcName}`
17
+ );
18
+ }
19
+ return func(value);
20
+ };