@jupyterlab/ui-components 4.7.0-beta.0 → 4.7.0-beta.2

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.
@@ -0,0 +1,338 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import type { ITranslator, TranslationBundle } from '@jupyterlab/translation';
5
+ import { nullTranslator } from '@jupyterlab/translation';
6
+ import type { IDisposable } from '@lumino/disposable';
7
+ import type { ISignal } from '@lumino/signaling';
8
+ import { Signal } from '@lumino/signaling';
9
+ import type { AccordionPanel, Widget } from '@lumino/widgets';
10
+
11
+ /**
12
+ * Opt-in drag reordering shared by sidebar accordion panels.
13
+ */
14
+ export class AccordionPanelReorderer
15
+ implements IDisposable, EventListenerObject
16
+ {
17
+ /**
18
+ * Get or create the reorderer for a panel.
19
+ */
20
+ static get(
21
+ panel: AccordionPanel,
22
+ translator: ITranslator = nullTranslator
23
+ ): AccordionPanelReorderer {
24
+ let reorderer = this._instances.get(panel.node);
25
+ if (!reorderer) {
26
+ reorderer = new AccordionPanelReorderer(panel, translator);
27
+ this._instances.set(panel.node, reorderer);
28
+ }
29
+ return reorderer;
30
+ }
31
+
32
+ /**
33
+ * Find the reorderer associated with an accordion node.
34
+ */
35
+ static find(node: HTMLElement): AccordionPanelReorderer | undefined {
36
+ return this._instances.get(node);
37
+ }
38
+
39
+ /**
40
+ * Whether drag reordering is enabled in every accordion panel.
41
+ */
42
+ static get enabled(): boolean {
43
+ return this._enabled;
44
+ }
45
+ static set enabled(value: boolean) {
46
+ if (value === this._enabled) {
47
+ return;
48
+ }
49
+ this._enabled = value;
50
+ this._enabledChanged.emit(value);
51
+ }
52
+
53
+ /**
54
+ * A signal emitted when drag reordering is enabled or disabled.
55
+ */
56
+ static get enabledChanged(): ISignal<
57
+ typeof AccordionPanelReorderer,
58
+ boolean
59
+ > {
60
+ return this._enabledChanged;
61
+ }
62
+
63
+ private constructor(
64
+ private _panel: AccordionPanel,
65
+ translator: ITranslator
66
+ ) {
67
+ this._trans = translator.load('jupyterlab');
68
+ this._indicator.className = 'jp-AccordionPanel-dropIndicator';
69
+ this._indicator.style.display = 'none';
70
+ _panel.node.appendChild(this._indicator);
71
+ this._onEnabledChanged();
72
+ AccordionPanelReorderer._enabledChanged.connect(
73
+ this._onEnabledChanged,
74
+ this
75
+ );
76
+ this._observer = new MutationObserver(() => this._updateHandles());
77
+ this._observer.observe(_panel.node, { childList: true });
78
+ for (const type of [
79
+ 'pointerdown',
80
+ 'pointermove',
81
+ 'pointerup',
82
+ 'pointercancel',
83
+ 'lostpointercapture'
84
+ ]) {
85
+ _panel.node.addEventListener(type, this);
86
+ }
87
+ _panel.disposed.connect(this.dispose, this);
88
+ }
89
+
90
+ /**
91
+ * The accordion panel whose sections are reordered.
92
+ */
93
+ get panel(): AccordionPanel {
94
+ return this._panel;
95
+ }
96
+
97
+ /**
98
+ * A signal emitted after a section is reordered.
99
+ */
100
+ get reordered(): ISignal<this, Widget> {
101
+ return this._reordered;
102
+ }
103
+
104
+ /**
105
+ * Move a section to another index, as a drop does.
106
+ */
107
+ move(widget: Widget, index: number): void {
108
+ const current = this._panel.widgets.indexOf(widget);
109
+ if (
110
+ current < 0 ||
111
+ index === current ||
112
+ index < 0 ||
113
+ index >= this._panel.widgets.length
114
+ ) {
115
+ return;
116
+ }
117
+ this._panel.insertWidget(index, widget);
118
+ // Lumino only repositions the section, so move its title, body and
119
+ // handle to keep the Tab order the same as the visual order.
120
+ const next = this._panel.titles[index + 1] ?? null;
121
+ for (const node of [
122
+ this._panel.titles[index],
123
+ widget.node,
124
+ this._panel.handles[index]
125
+ ]) {
126
+ this._panel.node.insertBefore(node, next);
127
+ }
128
+ this._reordered.emit(widget);
129
+ }
130
+
131
+ /**
132
+ * Whether the reorderer has been disposed.
133
+ */
134
+ get isDisposed(): boolean {
135
+ return this._isDisposed;
136
+ }
137
+
138
+ /**
139
+ * Remove event listeners and drag controls.
140
+ */
141
+ dispose(): void {
142
+ if (this._isDisposed) {
143
+ return;
144
+ }
145
+ this._isDisposed = true;
146
+ this._endDrag();
147
+ this._panel.removeClass('jp-mod-reorderable');
148
+ this._observer.disconnect();
149
+ for (const type of [
150
+ 'pointerdown',
151
+ 'pointermove',
152
+ 'pointerup',
153
+ 'pointercancel',
154
+ 'lostpointercapture'
155
+ ]) {
156
+ this._panel.node.removeEventListener(type, this);
157
+ }
158
+ this._panel.node
159
+ .querySelectorAll('.jp-AccordionPanel-dragHandle')
160
+ .forEach(handle => handle.remove());
161
+ this._indicator.remove();
162
+ AccordionPanelReorderer._instances.delete(this._panel.node);
163
+ Signal.clearData(this);
164
+ }
165
+
166
+ /**
167
+ * Handle pointer events from the panel's drag handles.
168
+ */
169
+ handleEvent(event: Event): void {
170
+ if (event.type === 'keydown') {
171
+ if (this._draggedWidget && (event as KeyboardEvent).key === 'Escape') {
172
+ this._endDrag();
173
+ event.preventDefault();
174
+ event.stopPropagation();
175
+ }
176
+ return;
177
+ }
178
+ const pointer = event as PointerEvent;
179
+ if (event.type === 'pointerdown') {
180
+ const target = event.target;
181
+ if (
182
+ !AccordionPanelReorderer.enabled ||
183
+ this._pointerId !== null ||
184
+ pointer.button !== 0 ||
185
+ !(target instanceof HTMLElement) ||
186
+ !target.closest('.jp-AccordionPanel-dragHandle')
187
+ ) {
188
+ return;
189
+ }
190
+ const title = target.closest('.lm-AccordionPanel-title');
191
+ const index = this._panel.titles.findIndex(node => node === title);
192
+ if (index < 0) {
193
+ return;
194
+ }
195
+ this._draggedWidget = this._panel.widgets[index];
196
+ this._start = this._coordinate(pointer);
197
+ this._pointerId = pointer.pointerId;
198
+ this._panel.node.setPointerCapture(pointer.pointerId);
199
+ this._panel.node.ownerDocument.addEventListener('keydown', this, true);
200
+ event.preventDefault();
201
+ } else if (pointer.pointerId === this._pointerId) {
202
+ switch (event.type) {
203
+ case 'pointermove': {
204
+ const position = this._coordinate(pointer);
205
+ if (Math.abs(position - this._start) > 5) {
206
+ this._isDragging = true;
207
+ this._panel.addClass('jp-mod-dragging');
208
+ }
209
+ if (this._isDragging) {
210
+ this._showIndicator(this._getTargetSlot(position));
211
+ }
212
+ break;
213
+ }
214
+ case 'pointerup':
215
+ this._endDrag(this._coordinate(pointer));
216
+ break;
217
+ case 'pointercancel':
218
+ case 'lostpointercapture':
219
+ this._endDrag();
220
+ break;
221
+ }
222
+ }
223
+ }
224
+
225
+ private _onEnabledChanged(): void {
226
+ this._panel.toggleClass(
227
+ 'jp-mod-reorderable',
228
+ AccordionPanelReorderer.enabled
229
+ );
230
+ if (!AccordionPanelReorderer.enabled) {
231
+ this._endDrag();
232
+ }
233
+ this._updateHandles();
234
+ }
235
+
236
+ private _updateHandles(): void {
237
+ for (const title of this._panel.titles) {
238
+ if (!title.querySelector('.jp-AccordionPanel-dragHandle')) {
239
+ const handle = document.createElement('span');
240
+ handle.className = 'jp-AccordionPanel-dragHandle';
241
+ handle.setAttribute('aria-hidden', 'true');
242
+ handle.title = this._trans.__('Drag to reorder');
243
+ title.prepend(handle);
244
+ }
245
+ }
246
+ }
247
+
248
+ private _coordinate(event: PointerEvent): number {
249
+ return this._panel.orientation === 'horizontal'
250
+ ? event.clientX
251
+ : event.clientY;
252
+ }
253
+
254
+ private _getTargetSlot(position: number): number {
255
+ const horizontal = this._panel.orientation === 'horizontal';
256
+ const slot = this._panel.titles.findIndex(title => {
257
+ const rect = title.getBoundingClientRect();
258
+ return (
259
+ position <
260
+ (horizontal ? rect.left + rect.width / 2 : rect.top + rect.height / 2)
261
+ );
262
+ });
263
+ return slot < 0 ? this._panel.titles.length : slot;
264
+ }
265
+
266
+ private _showIndicator(slot: number): void {
267
+ const titles = this._panel.titles;
268
+ if (!titles.length) {
269
+ return;
270
+ }
271
+ const horizontal = this._panel.orientation === 'horizontal';
272
+ const last = this._panel.widgets[titles.length - 1];
273
+ // After the last section, the line goes below its body when it is expanded.
274
+ const rect = (
275
+ titles[slot] ?? (last.isHidden ? titles[titles.length - 1] : last.node)
276
+ ).getBoundingClientRect();
277
+ const panelRect = this._panel.node.getBoundingClientRect();
278
+ const edge = horizontal
279
+ ? slot < titles.length
280
+ ? rect.left
281
+ : rect.right
282
+ : slot < titles.length
283
+ ? rect.top
284
+ : rect.bottom;
285
+ this._indicator.style.left = horizontal ? `${edge - panelRect.left}px` : '';
286
+ this._indicator.style.top = horizontal ? '' : `${edge - panelRect.top}px`;
287
+ // Draw the line before the far edge, so that it stays inside the panel.
288
+ this._indicator.style.transform =
289
+ slot < titles.length
290
+ ? ''
291
+ : horizontal
292
+ ? 'translateX(-100%)'
293
+ : 'translateY(-100%)';
294
+ this._indicator.style.display = 'block';
295
+ }
296
+
297
+ private _endDrag(position?: number): void {
298
+ const widget = this._draggedWidget;
299
+ const dragging = this._isDragging;
300
+ const pointerId = this._pointerId;
301
+ this._draggedWidget = null;
302
+ this._isDragging = false;
303
+ this._pointerId = null;
304
+ this._indicator.style.display = 'none';
305
+ this._panel.removeClass('jp-mod-dragging');
306
+ this._panel.node.ownerDocument.removeEventListener('keydown', this, true);
307
+ if (pointerId !== null && this._panel.node.hasPointerCapture(pointerId)) {
308
+ this._panel.node.releasePointerCapture(pointerId);
309
+ }
310
+ if (dragging && widget && position !== undefined) {
311
+ const current = this._panel.widgets.indexOf(widget);
312
+ if (current < 0) {
313
+ return;
314
+ }
315
+ const slot = this._getTargetSlot(position);
316
+ this.move(widget, slot > current ? slot - 1 : slot);
317
+ }
318
+ }
319
+
320
+ private static _instances = new WeakMap<
321
+ HTMLElement,
322
+ AccordionPanelReorderer
323
+ >();
324
+ private static _enabled = false;
325
+ private static _enabledChanged = new Signal<
326
+ typeof AccordionPanelReorderer,
327
+ boolean
328
+ >(AccordionPanelReorderer);
329
+ private _trans: TranslationBundle;
330
+ private _observer: MutationObserver;
331
+ private _indicator = document.createElement('div');
332
+ private _isDisposed = false;
333
+ private _draggedWidget: Widget | null = null;
334
+ private _pointerId: number | null = null;
335
+ private _start = 0;
336
+ private _isDragging = false;
337
+ private _reordered = new Signal<this, Widget>(this);
338
+ }
@@ -614,7 +614,7 @@ export interface IFormComponentProps<T = ReadonlyJSONObject>
614
614
  /**
615
615
  *
616
616
  */
617
- onChange: (e: IChangeEvent<T>) => any;
617
+ onChange: (e: IChangeEvent<T>, id?: string) => any;
618
618
  /**
619
619
  *
620
620
  */
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) Jupyter Development Team.
2
2
  // Distributed under the terms of the Modified BSD License.
3
3
 
4
+ export * from './accordionpanelreorderer';
4
5
  export * from './accordiontoolbar';
5
6
  export * from './button';
6
7
  export * from './collapser';
@@ -8,6 +8,21 @@ import { Search } from '@jupyter/react-components';
8
8
  import { searchIcon } from '../icon';
9
9
  import type { ISignal } from '@lumino/signaling';
10
10
 
11
+ /**
12
+ * A suggestion shown under the filter box.
13
+ */
14
+ export interface IFilterSuggestion {
15
+ /**
16
+ * The text shown in the list of suggestions.
17
+ */
18
+ label: string;
19
+
20
+ /**
21
+ * The query set in the filter box when the suggestion is picked.
22
+ */
23
+ value: string;
24
+ }
25
+
11
26
  /**
12
27
  * The class name added to the filebrowser crumbs node.
13
28
  */
@@ -27,6 +42,11 @@ export interface IFilterBoxProps {
27
42
  */
28
43
  forceRefresh?: boolean;
29
44
 
45
+ /**
46
+ * Get the suggestions to show under the filter box for a query.
47
+ */
48
+ getSuggestions?: (query: string) => IFilterSuggestion[];
49
+
30
50
  /**
31
51
  * An optional initial search value.
32
52
  */
@@ -201,6 +221,25 @@ export const FilterBox = (props: IFilterBoxProps): JSX.Element => {
201
221
  }
202
222
  }, [props.updateFilter, props.useFuzzyFilter, props.caseSensitive]);
203
223
 
224
+ const [suggestions, setSuggestions] = useState<IFilterSuggestion[]>([]);
225
+ const searchRef = useRef<HTMLInputElement | null>(null);
226
+ const listRef = useRef<HTMLUListElement>(null);
227
+ const [listId] = useState(
228
+ () => `jp-FilterBox-suggestions-${Private.nextId++}`
229
+ );
230
+ const [activeIndex, setActiveIndex] = useState(-1);
231
+ const setSearchRef = useCallback(
232
+ (node: HTMLInputElement | null) => {
233
+ searchRef.current = node;
234
+ if (props.inputRef) {
235
+ (
236
+ props.inputRef as React.MutableRefObject<HTMLInputElement | null>
237
+ ).current = node;
238
+ }
239
+ },
240
+ [props.inputRef]
241
+ );
242
+
204
243
  /**
205
244
  * Handler for search input changes.
206
245
  */
@@ -208,6 +247,7 @@ export const FilterBox = (props: IFilterBoxProps): JSX.Element => {
208
247
  (e: Event) => {
209
248
  const target = e.target as HTMLInputElement;
210
249
  setFilter(target.value);
250
+ setSuggestions(props.getSuggestions?.(target.value) ?? []);
211
251
  props.updateFilter(
212
252
  updateFilterFunction(
213
253
  target.value,
@@ -217,27 +257,144 @@ export const FilterBox = (props: IFilterBoxProps): JSX.Element => {
217
257
  target.value
218
258
  );
219
259
  },
220
- [props.updateFilter, props.useFuzzyFilter, props.caseSensitive]
260
+ [
261
+ props.updateFilter,
262
+ props.useFuzzyFilter,
263
+ props.caseSensitive,
264
+ props.getSuggestions
265
+ ]
221
266
  );
222
267
 
268
+ const options = (): HTMLElement[] =>
269
+ Array.from(
270
+ listRef.current?.querySelectorAll<HTMLElement>('[role="option"]') ?? []
271
+ );
272
+
273
+ /**
274
+ * Set the query of a suggestion in the filter box.
275
+ */
276
+ const pickSuggestion = (suggestion: IFilterSuggestion) => {
277
+ // The value attribute only sets the initial value of the search box.
278
+ if (searchRef.current) {
279
+ searchRef.current.value = suggestion.value;
280
+ }
281
+ setFilter(suggestion.value);
282
+ setSuggestions([]);
283
+ props.updateFilter(
284
+ updateFilterFunction(
285
+ suggestion.value,
286
+ props.useFuzzyFilter,
287
+ props.caseSensitive
288
+ ),
289
+ suggestion.value
290
+ );
291
+ searchRef.current?.focus();
292
+ };
293
+
294
+ const handleSearchKeyDown = (e: React.KeyboardEvent) => {
295
+ if (e.key === 'ArrowDown' && suggestions.length > 0) {
296
+ e.preventDefault();
297
+ options()[0]?.focus();
298
+ } else if (e.key === 'Escape' && suggestions.length > 0) {
299
+ e.stopPropagation();
300
+ setSuggestions([]);
301
+ }
302
+ };
303
+
304
+ const handleOptionKeyDown = (
305
+ e: React.KeyboardEvent,
306
+ suggestion: IFilterSuggestion,
307
+ index: number
308
+ ) => {
309
+ const items = options();
310
+ switch (e.key) {
311
+ case 'ArrowDown':
312
+ e.preventDefault();
313
+ items[Math.min(index + 1, items.length - 1)]?.focus();
314
+ break;
315
+ case 'ArrowUp':
316
+ e.preventDefault();
317
+ if (index === 0) {
318
+ searchRef.current?.focus();
319
+ } else {
320
+ items[index - 1]?.focus();
321
+ }
322
+ break;
323
+ case 'Enter':
324
+ e.preventDefault();
325
+ pickSuggestion(suggestion);
326
+ break;
327
+ case 'Escape':
328
+ e.preventDefault();
329
+ e.stopPropagation();
330
+ setSuggestions([]);
331
+ searchRef.current?.focus();
332
+ break;
333
+ }
334
+ };
335
+
336
+ const handleBlur = (e: React.FocusEvent) => {
337
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
338
+ setSuggestions([]);
339
+ }
340
+ };
341
+
223
342
  // Show the icon by default, or if the caller specifically requests it
224
343
  const showSearchIcon = props.showIcon ?? true;
225
344
 
226
345
  // Cast typing is required because HTMLInputElement and JupyterSearch element types don't exactly match
227
- return (
346
+ const search = (
228
347
  <Search
229
348
  role="search"
230
349
  className="jp-FilterBox"
231
- ref={props.inputRef as React.Ref<any>}
350
+ ref={setSearchRef as React.Ref<any>}
232
351
  value={filter}
233
352
  onChange={handleChange}
234
353
  onInput={handleChange}
354
+ onKeyDown={props.getSuggestions ? handleSearchKeyDown : undefined}
235
355
  placeholder={props.placeholder}
236
356
  disabled={props.disabled}
357
+ aria-controls={props.getSuggestions ? listId : undefined}
358
+ aria-expanded={props.getSuggestions ? suggestions.length > 0 : undefined}
237
359
  >
238
360
  {showSearchIcon && <searchIcon.react slot="end" tag={null} />}
239
361
  </Search>
240
362
  );
363
+
364
+ if (!props.getSuggestions) {
365
+ return search;
366
+ }
367
+
368
+ return (
369
+ <div className="jp-FilterBox-wrapper" onBlur={handleBlur}>
370
+ {search}
371
+ {suggestions.length > 0 && (
372
+ <ul
373
+ ref={listRef}
374
+ id={listId}
375
+ role="listbox"
376
+ className="jp-FilterBox-suggestions"
377
+ >
378
+ {suggestions.map((suggestion, index) => (
379
+ <li
380
+ key={suggestion.value}
381
+ role="option"
382
+ aria-selected={index === activeIndex}
383
+ tabIndex={-1}
384
+ className="jp-FilterBox-suggestion"
385
+ onMouseDown={e => e.preventDefault()}
386
+ onClick={() => pickSuggestion(suggestion)}
387
+ onFocus={() => setActiveIndex(index)}
388
+ onBlur={() => setActiveIndex(-1)}
389
+ onKeyDown={e => handleOptionKeyDown(e, suggestion, index)}
390
+ >
391
+ {suggestion.label}
392
+ </li>
393
+ ))}
394
+ </ul>
395
+ )}
396
+ </div>
397
+ );
241
398
  };
242
399
 
243
400
  /**
@@ -273,3 +430,10 @@ class FilenameSearcherWidget extends ReactWidget {
273
430
  export const FilenameSearcher = (props: IFilterBoxProps): ReactWidget => {
274
431
  return new FilenameSearcherWidget(props);
275
432
  };
433
+
434
+ namespace Private {
435
+ /**
436
+ * The id of the next list of suggestions.
437
+ */
438
+ export let nextId = 0;
439
+ }
@@ -4,6 +4,7 @@
4
4
  import type { ITranslator, TranslationBundle } from '@jupyterlab/translation';
5
5
  import { nullTranslator } from '@jupyterlab/translation';
6
6
  import { AccordionPanel, Panel, PanelLayout, Widget } from '@lumino/widgets';
7
+ import { AccordionPanelReorderer } from './accordionpanelreorderer';
7
8
  import { AccordionToolbar } from './accordiontoolbar';
8
9
  import { Toolbar } from './toolbar';
9
10
 
@@ -13,6 +14,7 @@ import { Toolbar } from './toolbar';
13
14
  * #### Note
14
15
  * By default the content widget is an accordion panel that supports widget with
15
16
  * associated toolbar to be displayed in the widget title.
17
+ * Give content widgets stable, unique IDs to persist their order and state.
16
18
  */
17
19
  export class SidePanel extends Widget {
18
20
  constructor(options: SidePanel.IOptions = {}) {
@@ -39,6 +41,10 @@ export class SidePanel extends Widget {
39
41
  content.addClass('jp-SidePanel-content');
40
42
  layout.addWidget(content);
41
43
 
44
+ if (content instanceof AccordionPanel) {
45
+ AccordionPanelReorderer.get(content, options.translator);
46
+ }
47
+
42
48
  if (options.toolbar) {
43
49
  this.addToolbar(options.toolbar);
44
50
  }