dash-core-components 4.0.0 → 4.2.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 (36) 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-graph.js +1 -1
  6. package/dash_core_components/async-graph.js.map +1 -1
  7. package/dash_core_components/async-highlight.js +1 -1
  8. package/dash_core_components/async-highlight.js.map +1 -1
  9. package/dash_core_components/async-markdown.js +1 -1
  10. package/dash_core_components/async-markdown.js.map +1 -1
  11. package/dash_core_components/async-slider.js.map +1 -1
  12. package/dash_core_components/async-upload.js.map +1 -1
  13. package/dash_core_components/dash_core_components-shared.js +1 -1
  14. package/dash_core_components/dash_core_components-shared.js.map +1 -1
  15. package/dash_core_components/dash_core_components.js +1 -1
  16. package/dash_core_components/dash_core_components.js.map +1 -1
  17. package/dash_core_components/proptypes.js +2 -0
  18. package/lib/components/Checklist.tsx +1 -1
  19. package/lib/components/Graph.react.js +5 -1
  20. package/lib/components/Input.tsx +2 -2
  21. package/lib/components/RadioItems.tsx +1 -1
  22. package/lib/components/css/datepickers.css +5 -0
  23. package/lib/components/css/dropdown.css +18 -0
  24. package/lib/components/css/sliders.css +1 -0
  25. package/lib/fragments/DatePickerRange.tsx +56 -5
  26. package/lib/fragments/DatePickerSingle.tsx +15 -1
  27. package/lib/fragments/Dropdown.tsx +242 -131
  28. package/lib/fragments/Graph.react.js +31 -4
  29. package/lib/types.ts +12 -0
  30. package/lib/utils/calendar/Calendar.tsx +1 -3
  31. package/lib/utils/calendar/helpers.ts +1 -0
  32. package/lib/utils/dropdownSearch.ts +54 -43
  33. package/lib/utils/optionRendering.tsx +287 -43
  34. package/lib/utils/optionTypes.ts +25 -11
  35. package/package.json +5 -4
  36. package/dash_core_components/plotly.min.js +0 -8
@@ -35,6 +35,7 @@ function convertFormatTokens(momentFormat: string): string {
35
35
  .replace(/Do/g, 'do') // Ordinal day: 1st, 2nd, 3rd
36
36
  .replace(/YYYY/g, 'yyyy') // 4-digit year
37
37
  .replace(/YY/g, 'yy') // 2-digit year
38
+ .replace(/Y/g, 'y') // Year (numeric, variable length)
38
39
  .replace(/DD/g, 'dd') // Day of month with leading zero
39
40
  .replace(/D/g, 'd') // Day of month
40
41
  .replace(/X/g, 't'); // Unix timestamp (seconds)
@@ -5,7 +5,7 @@ import {
5
5
  UnorderedSearchIndex,
6
6
  } from 'js-search';
7
7
  import {sanitizeOptions} from './optionTypes';
8
- import {DetailedOption, DropdownProps} from '../types';
8
+ import {DetailedOption, DropdownProps, OptionValue} from '../types';
9
9
 
10
10
  // Custom tokenizer, see https://github.com/bvaughn/js-search/issues/43
11
11
  // Split on spaces
@@ -19,38 +19,35 @@ const TOKENIZER = {
19
19
  },
20
20
  };
21
21
 
22
- interface FilteredOptionsResult {
23
- sanitizedOptions: DetailedOption[];
24
- filteredOptions: DetailedOption[];
22
+ export interface SanitizedOptions {
23
+ options: DetailedOption[];
24
+ indexes: string[];
25
+ valueSet: Set<OptionValue>;
26
+ search: Search;
25
27
  }
26
28
 
27
- /**
28
- * Creates filtered dropdown options using js-search with the exact same behavior
29
- * as react-select-fast-filter-options
30
- */
31
- export function createFilteredOptions(
32
- options: DropdownProps['options'],
33
- searchable: boolean,
34
- searchValue?: string
35
- ): FilteredOptionsResult {
36
- // Sanitize and prepare options
37
- let sanitized = sanitizeOptions(options);
29
+ // Single-pass sanitization via sanitizeOptions, plus detection of
30
+ // search/element labels for indexing.
31
+ export function sanitizeDropdownOptions(
32
+ options: DropdownProps['options']
33
+ ): SanitizedOptions {
34
+ const {options: sanitized, valueSet} = sanitizeOptions(options);
38
35
 
39
36
  const indexes = ['value'];
40
37
  let hasElement = false,
41
38
  hasSearch = false;
42
39
 
43
- sanitized = Array.isArray(sanitized)
44
- ? sanitized.map(option => {
45
- if (option.search) {
46
- hasSearch = true;
47
- }
48
- if (React.isValidElement(option.label)) {
49
- hasElement = true;
50
- }
51
- return option;
52
- })
53
- : sanitized;
40
+ for (const option of sanitized) {
41
+ if (option.search) {
42
+ hasSearch = true;
43
+ }
44
+ if (React.isValidElement(option.label)) {
45
+ hasElement = true;
46
+ }
47
+ if (hasSearch && hasElement) {
48
+ break;
49
+ }
50
+ }
54
51
 
55
52
  if (!hasElement) {
56
53
  indexes.push('label');
@@ -59,34 +56,48 @@ export function createFilteredOptions(
59
56
  indexes.push('search');
60
57
  }
61
58
 
62
- // If not searchable or no search value, return all sanitized options
63
- if (!searchable || !searchValue) {
64
- return {
65
- sanitizedOptions: sanitized || [],
66
- filteredOptions: sanitized || [],
67
- };
68
- }
69
-
70
- // Create js-search instance exactly like react-select-fast-filter-options
71
- const search = new Search('value'); // valueKey defaults to 'value'
59
+ // Build the search index ONCE during sanitization
60
+ const search = new Search('value');
72
61
  search.searchIndex = new UnorderedSearchIndex();
73
62
  search.indexStrategy = new AllSubstringsIndexStrategy();
74
63
  search.tokenizer = TOKENIZER;
75
64
 
76
- // Add indexes
77
65
  indexes.forEach(index => {
78
66
  search.addIndex(index);
79
67
  });
80
68
 
81
- // Add documents
82
- if (sanitized && sanitized.length > 0) {
69
+ if (sanitized.length > 0) {
83
70
  search.addDocuments(sanitized);
84
71
  }
85
72
 
86
- const filtered = search.search(searchValue) as DetailedOption[];
87
-
88
73
  return {
89
- sanitizedOptions: sanitized || [],
90
- filteredOptions: filtered || [],
74
+ options: sanitized,
75
+ indexes,
76
+ valueSet,
77
+ search,
91
78
  };
92
79
  }
80
+
81
+ export function filterOptions(
82
+ options: SanitizedOptions,
83
+ searchValue?: DropdownProps['search_value'],
84
+ searchOrder?: DropdownProps['search_order']
85
+ ): DetailedOption[] {
86
+ if (!searchValue) {
87
+ return options.options;
88
+ }
89
+
90
+ const results =
91
+ (options.search.search(searchValue) as DetailedOption[]) || [];
92
+
93
+ // Preserve original option order
94
+ if (searchOrder === 'original') {
95
+ const resultSet = new Set(results.map(option => option.value));
96
+
97
+ return options.options.filter(option =>
98
+ resultSet.has(option.value)
99
+ );
100
+ }
101
+
102
+ return results;
103
+ }
@@ -1,8 +1,20 @@
1
- import React from 'react';
1
+ import React, {
2
+ forwardRef,
3
+ memo,
4
+ useCallback,
5
+ useImperativeHandle,
6
+ useLayoutEffect,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ } from 'react';
2
11
  import {append, includes, without} from 'ramda';
12
+ import {VariableSizeList, ListChildComponentProps} from 'react-window';
3
13
  import {DetailedOption, OptionValue} from 'src/types';
4
14
  import '../components/css/optionslist.css';
5
15
 
16
+ const DEFAULT_ITEM_HEIGHT = 35;
17
+
6
18
  interface StylingProps {
7
19
  id?: string;
8
20
  className?: string;
@@ -37,7 +49,7 @@ export const OptionLabel: React.FC<OptionLabelProps> = ({
37
49
  <ExternalWrapper
38
50
  key={i}
39
51
  component={label}
40
- componentPath={[...ctx.componentPath, index, i]}
52
+ componentPath={[...ctx.componentPath, String(value), i]}
41
53
  />
42
54
  ))}
43
55
  </>
@@ -91,6 +103,7 @@ export const Option: React.FC<OptionProps> = ({
91
103
  role="option"
92
104
  aria-selected={isSelected}
93
105
  style={optionStyle}
106
+ data-option-index={index}
94
107
  >
95
108
  <span className="dash-options-list-option-wrapper">
96
109
  <input
@@ -125,51 +138,282 @@ export const Option: React.FC<OptionProps> = ({
125
138
  );
126
139
  };
127
140
 
128
- interface OptionsListProps extends StylingProps {
141
+ interface RowData {
129
142
  options: DetailedOption[];
130
143
  selected: OptionValue[];
131
- onSelectionChange: (selected: OptionValue[]) => void;
144
+ onChange: (option: DetailedOption) => void;
145
+ passThruProps: StylingProps;
146
+ setOptionHeight: (index: number, height: number) => void;
132
147
  }
133
148
 
134
- export const OptionsList: React.FC<OptionsListProps> = ({
135
- options,
136
- selected,
137
- onSelectionChange,
138
- id,
139
- className,
140
- style,
141
- ...passThruProps
142
- }) => {
143
- const classNames = ['dash-options-list', className].filter(Boolean);
149
+ const Row = memo(({index, style, data}: ListChildComponentProps<RowData>) => {
150
+ const {options, selected, onChange, passThruProps, setOptionHeight} = data;
151
+ const option = options[index];
152
+ const isSelected = includes(option.value, selected);
153
+
154
+ const measureRef = useCallback(
155
+ (el: HTMLDivElement | null) => {
156
+ if (!el) {
157
+ return;
158
+ }
159
+ // Synchronous measurement for string labels.
160
+ const immediateHeight = el.getBoundingClientRect().height;
161
+ if (immediateHeight > 0) {
162
+ setOptionHeight(index, immediateHeight);
163
+ }
164
+
165
+ // ResizeObserver catches async Dash component labels
166
+ // that render after the initial commit.
167
+ const observer = new ResizeObserver(([entry]) => {
168
+ const height =
169
+ entry.borderBoxSize?.[0]?.blockSize ??
170
+ entry.contentRect.height;
171
+ if (height > 0) {
172
+ setOptionHeight(index, height);
173
+ }
174
+ });
175
+ observer.observe(el);
176
+ },
177
+ [index, setOptionHeight]
178
+ );
179
+
144
180
  return (
145
- <div
146
- id={id}
147
- className={classNames.join(' ')}
148
- style={style}
149
- role="listbox"
150
- >
151
- {options.map((option, i) => {
152
- const isSelected = includes(option.value, selected);
153
- return (
154
- <Option
155
- id={id}
156
- key={i}
157
- index={i}
158
- option={option}
159
- isSelected={isSelected}
160
- onChange={option => {
161
- let newValue: OptionValue[];
162
- if (includes(option.value, selected)) {
163
- newValue = without([option.value], selected);
164
- } else {
165
- newValue = append(option.value, selected);
166
- }
167
- onSelectionChange(newValue);
168
- }}
169
- {...passThruProps}
170
- />
171
- );
172
- })}
181
+ <div style={style}>
182
+ <div ref={measureRef}>
183
+ <Option
184
+ id={passThruProps.id}
185
+ index={index}
186
+ option={option}
187
+ isSelected={isSelected}
188
+ onChange={onChange}
189
+ {...passThruProps}
190
+ />
191
+ </div>
173
192
  </div>
174
193
  );
175
- };
194
+ });
195
+
196
+ Row.displayName = 'Row';
197
+
198
+ export interface OptionsListHandle {
199
+ scrollToItem: (index: number) => void;
200
+ focusItem: (index: number) => void;
201
+ }
202
+
203
+ interface OptionsListProps extends StylingProps {
204
+ options: DetailedOption[];
205
+ selected: OptionValue[];
206
+ onSelectionChange: (selected: OptionValue[]) => void;
207
+ optionHeight?: number;
208
+ maxHeight?: number;
209
+ }
210
+
211
+ export const OptionsList = forwardRef<OptionsListHandle, OptionsListProps>(
212
+ (
213
+ {
214
+ options,
215
+ selected,
216
+ onSelectionChange,
217
+ optionHeight,
218
+ maxHeight = window.innerHeight,
219
+ id,
220
+ className,
221
+ style,
222
+ ...passThruProps
223
+ },
224
+ ref
225
+ ) => {
226
+ const listRef = useRef<VariableSizeList>(null);
227
+ const containerRef = useRef<HTMLDivElement>(null);
228
+ const pendingFocusRef = useRef<number | null>(null);
229
+ const heightsRef = useRef<Map<number, number>>(new Map());
230
+ const [measuredHeight, setMeasuredHeight] = useState<number | null>(
231
+ null
232
+ );
233
+
234
+ const defaultOptionHeight = optionHeight ?? DEFAULT_ITEM_HEIGHT;
235
+
236
+ const getOptionHeight = useCallback(
237
+ (index: number): number =>
238
+ heightsRef.current.get(index) ?? defaultOptionHeight,
239
+ [defaultOptionHeight]
240
+ );
241
+
242
+ const setOptionHeight = useCallback((index: number, height: number) => {
243
+ if (heightsRef.current.get(index) !== height) {
244
+ heightsRef.current.set(index, height);
245
+ listRef.current?.resetAfterIndex(index, true);
246
+ }
247
+ }, []);
248
+
249
+ // Measure container height before first paint. Row measureRefs
250
+ // have already fired, so invalidate the list's internal cache
251
+ // so the re-render picks up measured heights.
252
+ useLayoutEffect(() => {
253
+ const el = containerRef.current;
254
+ if (!el || measuredHeight !== null) {
255
+ return;
256
+ }
257
+ listRef.current?.resetAfterIndex(0, false);
258
+ const h = el.getBoundingClientRect().height;
259
+ if (h > 0) {
260
+ setMeasuredHeight(h);
261
+ }
262
+ }, []);
263
+
264
+ const defaultListHeight = options.length * defaultOptionHeight;
265
+ const listHeight =
266
+ measuredHeight === null
267
+ ? maxHeight
268
+ : Math.min(measuredHeight, defaultListHeight);
269
+
270
+ const focusOption = useCallback((optionIndex: number) => {
271
+ requestAnimationFrame(() => {
272
+ if (pendingFocusRef.current !== optionIndex) {
273
+ return;
274
+ }
275
+ const deferred = containerRef.current?.querySelector(
276
+ `[data-option-index="${optionIndex}"] input`
277
+ );
278
+ if (deferred instanceof HTMLElement) {
279
+ pendingFocusRef.current = null;
280
+ deferred.focus();
281
+ }
282
+ });
283
+ }, []);
284
+
285
+ useImperativeHandle(ref, () => ({
286
+ scrollToItem: (index: number) => {
287
+ if (listRef.current) {
288
+ listRef.current.scrollToItem(index, 'smart');
289
+ }
290
+ },
291
+ focusItem: (index: number) => {
292
+ pendingFocusRef.current = index;
293
+ if (listRef.current) {
294
+ listRef.current.scrollToItem(index, 'center');
295
+ }
296
+ focusOption(index);
297
+ },
298
+ }));
299
+
300
+ const handleChange = useCallback(
301
+ (option: DetailedOption) => {
302
+ let newValue: OptionValue[];
303
+ if (includes(option.value, selected)) {
304
+ newValue = without([option.value], selected);
305
+ } else {
306
+ newValue = append(option.value, selected);
307
+ }
308
+ onSelectionChange(newValue);
309
+ },
310
+ [selected, onSelectionChange]
311
+ );
312
+
313
+ const classNames = ['dash-options-list', className].filter(Boolean);
314
+
315
+ const handleItemsRendered = useCallback(() => {
316
+ if (typeof pendingFocusRef.current === 'number') {
317
+ focusOption(pendingFocusRef.current);
318
+ }
319
+ }, []);
320
+
321
+ // Render the longest-label option (sampled) for intrinsic width.
322
+ const sizerDiv = useMemo(() => {
323
+ if (!options.length) {
324
+ return null;
325
+ }
326
+ const step = Math.max(1, Math.floor(options.length / 100));
327
+ let longestOption = options[0];
328
+ let maxLen = 0;
329
+ for (let i = 0; i < options.length; i += step) {
330
+ const {label} = options[i];
331
+ if (typeof label !== 'string') {
332
+ return null;
333
+ }
334
+ if (label.length > maxLen) {
335
+ longestOption = options[i];
336
+ maxLen = label.length;
337
+ }
338
+ }
339
+ return (
340
+ <Option
341
+ index={-1}
342
+ option={longestOption}
343
+ isSelected={false}
344
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
345
+ onChange={() => {}}
346
+ />
347
+ );
348
+ }, [options]);
349
+
350
+ const itemData = useMemo<RowData>(
351
+ () => ({
352
+ options,
353
+ selected,
354
+ onChange: handleChange,
355
+ passThruProps: {id, ...passThruProps},
356
+ setOptionHeight,
357
+ }),
358
+ [options, selected, handleChange, id, passThruProps]
359
+ );
360
+
361
+ if (options.length < 100) {
362
+ return (
363
+ <div
364
+ ref={containerRef}
365
+ id={id}
366
+ className={classNames.join(' ')}
367
+ style={style}
368
+ role="listbox"
369
+ >
370
+ {options.map((option, i) => (
371
+ <Option
372
+ key={i}
373
+ id={id}
374
+ index={i}
375
+ option={option}
376
+ isSelected={includes(option.value, selected)}
377
+ onChange={handleChange}
378
+ {...passThruProps}
379
+ />
380
+ ))}
381
+ </div>
382
+ );
383
+ }
384
+
385
+ return (
386
+ <div
387
+ ref={containerRef}
388
+ id={id}
389
+ className={classNames.join(' ')}
390
+ style={style}
391
+ role="listbox"
392
+ >
393
+ <VariableSizeList
394
+ ref={listRef}
395
+ height={listHeight}
396
+ itemCount={options.length}
397
+ itemSize={getOptionHeight}
398
+ estimatedItemSize={defaultOptionHeight}
399
+ width="100%"
400
+ className="dash-options-list-virtualized"
401
+ onItemsRendered={handleItemsRendered}
402
+ itemData={itemData}
403
+ itemKey={(index, data) =>
404
+ String(data.options[index]?.value ?? index)
405
+ }
406
+ >
407
+ {Row}
408
+ </VariableSizeList>
409
+ {sizerDiv && (
410
+ <div aria-hidden style={{height: 0, overflow: 'hidden'}}>
411
+ {sizerDiv}
412
+ </div>
413
+ )}
414
+ </div>
415
+ );
416
+ }
417
+ );
418
+
419
+ OptionsList.displayName = 'OptionsList';
@@ -5,23 +5,37 @@ const isOptionValue = (option: unknown): option is OptionValue => {
5
5
  return ['string', 'number', 'boolean'].includes(typeof option);
6
6
  };
7
7
 
8
+ export interface SanitizedResult {
9
+ options: DetailedOption[];
10
+ valueSet: Set<OptionValue>;
11
+ }
12
+
8
13
  export const sanitizeOptions = (
9
14
  options: DropdownProps['options']
10
- ): DetailedOption[] => {
11
- if (typeof options === 'object' && !(options instanceof Array)) {
12
- return Object.entries(options).map(([value, label]) => ({
13
- label: React.isValidElement(label) ? label : String(label),
14
- value,
15
- }));
16
- }
15
+ ): SanitizedResult => {
16
+ const valueSet = new Set<OptionValue>();
17
+ let result: DetailedOption[];
17
18
 
18
- if (options instanceof Array) {
19
- return options.map(option => {
20
- return isOptionValue(option)
19
+ if (typeof options === 'object' && !(options instanceof Array)) {
20
+ result = Object.entries(options).map(([value, label]) => {
21
+ const opt = {
22
+ label: React.isValidElement(label) ? label : String(label),
23
+ value,
24
+ };
25
+ valueSet.add(value);
26
+ return opt;
27
+ });
28
+ } else if (options instanceof Array) {
29
+ result = options.map(option => {
30
+ const opt = isOptionValue(option)
21
31
  ? {label: String(option), value: option}
22
32
  : option;
33
+ valueSet.add(opt.value);
34
+ return opt;
23
35
  });
36
+ } else {
37
+ result = [];
24
38
  }
25
39
 
26
- return [];
40
+ return {options: result, valueSet};
27
41
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dash-core-components",
3
- "version": "4.0.0",
3
+ "version": "4.2.0",
4
4
  "description": "Core component suite for Dash",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,12 +47,12 @@
47
47
  "@radix-ui/react-tooltip": "^1.2.8",
48
48
  "base64-js": "^1.5.1",
49
49
  "d3-format": "^1.4.5",
50
+ "date-fns": "^4.1.0",
50
51
  "fast-isnumeric": "^1.1.4",
51
52
  "file-saver": "^2.0.5",
52
53
  "highlight.js": "^11.8.0",
53
54
  "js-search": "^2.0.1",
54
55
  "mathjax": "^3.2.2",
55
- "date-fns": "^4.1.0",
56
56
  "node-polyfill-webpack-plugin": "^2.0.1",
57
57
  "prop-types": "^15.8.1",
58
58
  "ramda": "^0.30.1",
@@ -62,7 +62,7 @@
62
62
  "react-fast-compare": "^3.2.2",
63
63
  "react-input-autosize": "^3.0.0",
64
64
  "react-markdown": "^4.3.1",
65
- "react-virtualized-select": "^3.1.3",
65
+ "react-window": "^1.8.11",
66
66
  "remark-math": "^3.0.1",
67
67
  "uniqid": "^5.4.0"
68
68
  },
@@ -86,6 +86,7 @@
86
86
  "@types/react": "^16.14.8",
87
87
  "@types/react-dom": "^16.9.13",
88
88
  "@types/react-input-autosize": "^2.2.4",
89
+ "@types/react-window": "^1.8.8",
89
90
  "@types/uniqid": "^5.3.4",
90
91
  "@typescript-eslint/eslint-plugin": "^5.59.7",
91
92
  "@typescript-eslint/parser": "^5.59.7",
@@ -125,6 +126,6 @@
125
126
  "react-dom": "16 - 19"
126
127
  },
127
128
  "browserslist": [
128
- "last 9 years and not dead"
129
+ "last 10 years and not dead"
129
130
  ]
130
131
  }