@jupyterlab/apputils 4.8.0-beta.0 → 4.8.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.
@@ -4,15 +4,26 @@
4
4
  |----------------------------------------------------------------------------*/
5
5
 
6
6
  import { searchIcon } from '@jupyterlab/ui-components';
7
+ import type {
8
+ ReadonlyJSONObject,
9
+ ReadonlyPartialJSONObject
10
+ } from '@lumino/coreutils';
11
+ import { JSONExt } from '@lumino/coreutils';
7
12
  import type { Message } from '@lumino/messaging';
8
- import type { CommandPalette } from '@lumino/widgets';
9
- import { Panel, Widget } from '@lumino/widgets';
13
+ import type { ISignal } from '@lumino/signaling';
14
+ import { Signal } from '@lumino/signaling';
15
+ import { CommandPalette, Panel, Widget } from '@lumino/widgets';
10
16
 
11
17
  /**
12
18
  * Class name identifying the input group with search icon.
13
19
  */
14
20
  const SEARCH_ICON_GROUP_CLASS = 'jp-SearchIconGroup';
15
21
 
22
+ /**
23
+ * The default maximum number of recent commands.
24
+ */
25
+ const DEFAULT_MAX_RECENT_COMMANDS = 5;
26
+
16
27
  /**
17
28
  * Wrap the command palette in a modal to make it more usable.
18
29
  */
@@ -184,3 +195,225 @@ export namespace ModalCommandPalette {
184
195
  restore?: () => void;
185
196
  }
186
197
  }
198
+
199
+ /**
200
+ * A command palette which pins the commands recently triggered from it to
201
+ * the top while the search query is empty.
202
+ *
203
+ * #### Notes
204
+ * Commands executed from a menu, a keyboard shortcut or the command registry
205
+ * are not tracked. Use `recentCommands` and `recentsChanged` to persist the
206
+ * history.
207
+ */
208
+ export class RecentsCommandPalette extends CommandPalette {
209
+ /**
210
+ * Construct a new recents command palette.
211
+ *
212
+ * @param options - The options for creating the command palette.
213
+ */
214
+ constructor(options: RecentsCommandPalette.IOptions) {
215
+ super(options);
216
+ if (options.maxRecentCommands !== undefined) {
217
+ this.maxRecentCommands = options.maxRecentCommands;
218
+ }
219
+ this.itemTriggered.connect(this._onItemTriggered, this);
220
+ }
221
+
222
+ /**
223
+ * The maximum number of recent commands.
224
+ *
225
+ * #### Notes
226
+ * Setting the limit to `0` disables the tracking and clears the history.
227
+ * Setting it to `Infinity` removes the limit. The default value is `5`.
228
+ */
229
+ get maxRecentCommands(): number {
230
+ return this._maxRecentCommands;
231
+ }
232
+
233
+ set maxRecentCommands(value: number) {
234
+ this._maxRecentCommands = Math.max(0, Math.floor(value)) || 0;
235
+ this.recentCommands = this._recentCommands;
236
+ }
237
+
238
+ /**
239
+ * The recent commands, from most to least recently triggered.
240
+ *
241
+ * #### Notes
242
+ * Assigned entries are deduplicated and truncated to `maxRecentCommands`.
243
+ */
244
+ get recentCommands(): ReadonlyArray<RecentsCommandPalette.IRecentCommand> {
245
+ return this._recentCommands;
246
+ }
247
+
248
+ set recentCommands(
249
+ value: ReadonlyArray<RecentsCommandPalette.IRecentCommand>
250
+ ) {
251
+ const recents: RecentsCommandPalette.IRecentCommand[] = [];
252
+ for (const entry of value) {
253
+ if (recents.length >= this._maxRecentCommands) {
254
+ break;
255
+ }
256
+ if (!recents.some(recent => Private.isSameCommand(recent, entry))) {
257
+ recents.push({ command: entry.command, args: entry.args });
258
+ }
259
+ }
260
+
261
+ const current = this._recentCommands;
262
+ if (
263
+ recents.length === current.length &&
264
+ recents.every((recent, i) => Private.isSameCommand(recent, current[i]))
265
+ ) {
266
+ return;
267
+ }
268
+
269
+ this._recentCommands = recents;
270
+ this._recentsChanged.emit(undefined);
271
+ this.refresh();
272
+ }
273
+
274
+ /**
275
+ * A signal emitted when the recent commands change.
276
+ */
277
+ get recentsChanged(): ISignal<this, void> {
278
+ return this._recentsChanged;
279
+ }
280
+
281
+ /**
282
+ * Test whether a command item matches a recent command.
283
+ */
284
+ isRecent(item: CommandPalette.IItem): boolean {
285
+ return this._recentCommands.some(recent =>
286
+ Private.isSameCommand(recent, item)
287
+ );
288
+ }
289
+
290
+ /**
291
+ * Create the search results for a query.
292
+ *
293
+ * #### Notes
294
+ * While the query is empty, the recent commands are pinned to the top,
295
+ * without a header, and any other item for a pinned command is dropped
296
+ * from the results. Otherwise, the default results are returned.
297
+ */
298
+ protected search(query: string): CommandPalette.SearchResult[] {
299
+ const recents = this._resolveRecentItems();
300
+ if (recents.length === 0 || query.trim()) {
301
+ return super.search(query);
302
+ }
303
+
304
+ const pinned = recents.map(
305
+ (item): CommandPalette.IItemResult => ({
306
+ type: 'item',
307
+ item,
308
+ indices: null
309
+ })
310
+ );
311
+ const others = this.items.filter(
312
+ item => !recents.some(recent => Private.isSameCommand(recent, item))
313
+ );
314
+ return [...pinned, ...CommandPalette.search(others, query)];
315
+ }
316
+
317
+ /**
318
+ * Get the index of the result to activate for new search results.
319
+ *
320
+ * #### Notes
321
+ * While the recent commands are pinned, the first enabled one is active,
322
+ * so that `Enter` runs it.
323
+ */
324
+ protected initialActiveIndex(
325
+ query: string,
326
+ results: ReadonlyArray<CommandPalette.SearchResult>
327
+ ): number {
328
+ const pinned = query.trim() ? 0 : this._resolveRecentItems().length;
329
+ if (pinned === 0) {
330
+ return super.initialActiveIndex(query, results);
331
+ }
332
+ return results
333
+ .slice(0, pinned)
334
+ .findIndex(result => result.type === 'item' && result.item.isEnabled);
335
+ }
336
+
337
+ /**
338
+ * Resolve the recent commands to the visible palette items.
339
+ *
340
+ * #### Notes
341
+ * Disabled items stay pinned, so that the pinned items do not move when
342
+ * the application context changes.
343
+ */
344
+ private _resolveRecentItems(): CommandPalette.IItem[] {
345
+ const items: CommandPalette.IItem[] = [];
346
+ for (const recent of this._recentCommands) {
347
+ const item = this.items.find(candidate =>
348
+ Private.isSameCommand(candidate, recent)
349
+ );
350
+ if (item?.isVisible) {
351
+ items.push(item);
352
+ }
353
+ }
354
+ return items;
355
+ }
356
+
357
+ /**
358
+ * Handle the `itemTriggered` signal of the command palette.
359
+ */
360
+ private _onItemTriggered(
361
+ sender: CommandPalette,
362
+ item: CommandPalette.IItem
363
+ ): void {
364
+ const { command, args } = item;
365
+ this.recentCommands = [{ command, args }, ...this._recentCommands];
366
+ }
367
+
368
+ private _maxRecentCommands = DEFAULT_MAX_RECENT_COMMANDS;
369
+ private _recentCommands: RecentsCommandPalette.IRecentCommand[] = [];
370
+ private _recentsChanged = new Signal<this, void>(this);
371
+ }
372
+
373
+ /**
374
+ * The namespace for the `RecentsCommandPalette` class statics.
375
+ */
376
+ export namespace RecentsCommandPalette {
377
+ /**
378
+ * An options object for creating a recents command palette.
379
+ */
380
+ export interface IOptions extends CommandPalette.IOptions {
381
+ /**
382
+ * The maximum number of recent commands. The default value is `5`.
383
+ */
384
+ maxRecentCommands?: number;
385
+ }
386
+
387
+ /**
388
+ * A recently triggered command.
389
+ *
390
+ * #### Notes
391
+ * The interface extends a JSON object so that the history can be saved.
392
+ */
393
+ export interface IRecentCommand extends ReadonlyPartialJSONObject {
394
+ /**
395
+ * The command which was triggered.
396
+ */
397
+ readonly command: string;
398
+
399
+ /**
400
+ * The arguments for the command.
401
+ */
402
+ readonly args: ReadonlyJSONObject;
403
+ }
404
+ }
405
+
406
+ /**
407
+ * The namespace for module private data.
408
+ */
409
+ namespace Private {
410
+ /**
411
+ * Test whether two entries refer to the same command and arguments.
412
+ */
413
+ export function isSameCommand(
414
+ a: RecentsCommandPalette.IRecentCommand | CommandPalette.IItem,
415
+ b: RecentsCommandPalette.IRecentCommand | CommandPalette.IItem
416
+ ): boolean {
417
+ return a.command === b.command && JSONExt.deepEqual(a.args, b.args);
418
+ }
419
+ }
package/src/dialog.tsx CHANGED
@@ -418,7 +418,10 @@ export class Dialog<T> extends Widget {
418
418
  case 'ArrowLeft': {
419
419
  const activeEl = document.activeElement;
420
420
 
421
- if (activeEl instanceof HTMLButtonElement) {
421
+ if (
422
+ activeEl instanceof HTMLButtonElement &&
423
+ this._buttonNodes.includes(activeEl)
424
+ ) {
422
425
  let idx = this._buttonNodes.indexOf(activeEl) - 1;
423
426
 
424
427
  // Handle a left arrows on the first button
@@ -436,7 +439,10 @@ export class Dialog<T> extends Widget {
436
439
  case 'ArrowRight': {
437
440
  const activeEl = document.activeElement;
438
441
 
439
- if (activeEl instanceof HTMLButtonElement) {
442
+ if (
443
+ activeEl instanceof HTMLButtonElement &&
444
+ this._buttonNodes.includes(activeEl)
445
+ ) {
440
446
  let idx = this._buttonNodes.indexOf(activeEl) + 1;
441
447
 
442
448
  // Handle a right arrows on the last button
@@ -462,18 +468,25 @@ export class Dialog<T> extends Widget {
462
468
  break;
463
469
  }
464
470
  case 'Enter': {
465
- event.stopPropagation();
466
- event.preventDefault();
467
-
468
- const activeEl = document.activeElement;
469
-
470
- if (activeEl instanceof HTMLButtonElement) {
471
- const index = this._buttonNodes.indexOf(activeEl);
472
- if (index !== -1) {
473
- this.resolve(index);
474
- }
475
- } else if (!(activeEl instanceof HTMLTextAreaElement)) {
476
- const index = this._defaultButton;
471
+ const activeEl = Private.deepActiveElement();
472
+ let index = -1;
473
+
474
+ if (
475
+ activeEl instanceof HTMLButtonElement &&
476
+ this._buttonNodes.includes(activeEl)
477
+ ) {
478
+ index = this._buttonNodes.indexOf(activeEl);
479
+ } else if (
480
+ // Enter sent to the dialog node itself, as `acceptDialog()` does.
481
+ event.target === this.node ||
482
+ Private.submitsOnEnter(activeEl)
483
+ ) {
484
+ index = this._defaultButton;
485
+ }
486
+ // Other elements, such as links and editors, handle Enter themselves.
487
+ if (index !== -1) {
488
+ event.stopPropagation();
489
+ event.preventDefault();
477
490
  this.resolve(index);
478
491
  }
479
492
  break;
@@ -944,6 +957,9 @@ export namespace Dialog {
944
957
  const handleKeyDown = (event: React.KeyboardEvent) => {
945
958
  const { key } = event;
946
959
  if (key === 'Enter' || key === ' ') {
960
+ // Keep the browser from passing the key on to the element that
961
+ // gets the focus back when the dialog closes.
962
+ event.preventDefault();
947
963
  reject();
948
964
  }
949
965
  };
@@ -1234,4 +1250,31 @@ namespace Private {
1234
1250
  ].join(',');
1235
1251
  return node.querySelectorAll(candidateSelectors)[0] as HTMLElement;
1236
1252
  }
1253
+
1254
+ /**
1255
+ * The focused element, looked up through open shadow roots.
1256
+ *
1257
+ * For a web component such as `<jp-search>`, `document.activeElement` is
1258
+ * the host, and the focused `<input>` is in its shadow root.
1259
+ */
1260
+ export function deepActiveElement(): Element | null {
1261
+ let el = document.activeElement;
1262
+ while (el?.shadowRoot?.activeElement) {
1263
+ el = el.shadowRoot.activeElement;
1264
+ }
1265
+ return el;
1266
+ }
1267
+
1268
+ /**
1269
+ * Whether Enter in the element submits the dialog, as it submits a form.
1270
+ *
1271
+ * Button-like inputs are excluded because the browser activates them on Enter.
1272
+ */
1273
+ export function submitsOnEnter(el: Element | null): boolean {
1274
+ return (
1275
+ el instanceof HTMLSelectElement ||
1276
+ (el instanceof HTMLInputElement &&
1277
+ !['button', 'submit', 'reset', 'image'].includes(el.type))
1278
+ );
1279
+ }
1237
1280
  }
@@ -858,7 +858,7 @@ export class SessionContext implements ISessionContext {
858
858
  const session = manager.connectTo({ model });
859
859
  this._handleNewSession(session);
860
860
  } catch (err) {
861
- void this._handleSessionError(err);
861
+ void this._handleSessionError(err as ServerConnection.ResponseError);
862
862
  return Promise.reject(err);
863
863
  }
864
864
  }
@@ -961,7 +961,7 @@ export class SessionContext implements ISessionContext {
961
961
  await this._session.changeKernel(model);
962
962
  } catch (err) {
963
963
  this._isChangingKernel = false;
964
- void this._handleSessionError(err);
964
+ void this._handleSessionError(err as ServerConnection.ResponseError);
965
965
  throw err;
966
966
  }
967
967
  this._isChangingKernel = false;
@@ -1006,7 +1006,7 @@ export class SessionContext implements ISessionContext {
1006
1006
  }
1007
1007
  return this._handleNewSession(session);
1008
1008
  } catch (err) {
1009
- void this._handleSessionError(err);
1009
+ void this._handleSessionError(err as ServerConnection.ResponseError);
1010
1010
  throw err;
1011
1011
  }
1012
1012
  }
@@ -1527,9 +1527,10 @@ export class SessionContextDialogs implements ISessionContext.IDialogs {
1527
1527
  restartBtn
1528
1528
  ],
1529
1529
  checkbox: {
1530
- label: trans.__('Do not ask me again.'),
1530
+ label: trans.__('Do not ask me again for now.'),
1531
1531
  caption: trans.__(
1532
- 'If checked, the kernel will restart without confirmation prompt in the future; you can change this back in the settings.'
1532
+ 'Applies until %1 is closed or the page is reloaded. To never ask, enable "Skip kernel restart Dialog" in the Kernel dialogs settings.',
1533
+ sessionContext.name
1533
1534
  )
1534
1535
  }
1535
1536
  });
@@ -563,8 +563,13 @@ export class ThemeManager implements IThemeManager {
563
563
  });
564
564
 
565
565
  // Need to force a redraw of the app here to avoid a Chrome rendering
566
- // bug that can leave the scrollbars in an invalid state
567
- this._host.hide();
566
+ // bug that can leave the scrollbars in an invalid state. Skip it before
567
+ // the host is attached: nothing is drawn yet, and a host attached while
568
+ // hidden gets its first layout from `show()`, which sizes children
569
+ // before their parents and loses the relative sizes of split panels.
570
+ if (this._host.isAttached) {
571
+ this._host.hide();
572
+ }
568
573
 
569
574
  // If we hide/show the widget too quickly, no redraw will happen.
570
575
  // requestAnimationFrame delays until after the next frame render.
package/src/tokens.ts CHANGED
@@ -346,6 +346,12 @@ export namespace ToolbarRegistry {
346
346
  toolbarItem: IWidget
347
347
  ) => Widget;
348
348
  }
349
+
350
+ /**
351
+ * The default arg property referring to the ID of the widget, that is the
352
+ * parent of the toolbar.
353
+ */
354
+ export const WIDGET_ID_ARG = 'widgetId';
349
355
  }
350
356
 
351
357
  /**
@@ -170,7 +170,7 @@ async function setToolbarItems(
170
170
  }
171
171
  });
172
172
  } catch (error) {
173
- if (error.name === 'TransformError') {
173
+ if (error instanceof Error && error.name === 'TransformError') {
174
174
  // Assume the existing transformer is the toolbar builder transformer
175
175
  // from another factory set up.
176
176
  listenPlugin = false;
@@ -195,8 +195,16 @@ async function setToolbarItems(
195
195
  // This is not optimal but safer because a toolbar item with the same
196
196
  // name cannot be inserted (it will be a no-op). But that could happen
197
197
  // if the settings are changing the items order.
198
+ const filtered = newItems.filter(item => !item.disabled);
199
+ // settings.changed fires for any change to the plugin's settings, so
200
+ // skip the rebuild when the toolbar definition itself did not change:
201
+ // clearing and re-adding identical items rebuilds every toolbar and
202
+ // can reorder its items.
203
+ if (JSONExt.deepEqual([...toolbarItems], filtered)) {
204
+ return;
205
+ }
198
206
  toolbarItems.clear();
199
- toolbarItems.pushAll(newItems.filter(item => !item.disabled));
207
+ toolbarItems.pushAll(filtered);
200
208
  };
201
209
 
202
210
  // Initialize the toolbar
@@ -249,7 +257,9 @@ async function setToolbarItems(
249
257
  * @param pluginId Settings plugin id
250
258
  * @param translator Translator
251
259
  * @param propertyId Toolbar definition key in the settings plugin
252
- * @returns List of toolbar widgets factory
260
+ * @returns List of toolbar widgets factory; its optional `commandArgs`, such
261
+ * as the id of the widget the commands act on, are added to the arguments
262
+ * of every item without overriding those the item sets
253
263
  */
254
264
  export function createToolbarFactory(
255
265
  toolbarRegistry: IToolbarWidgetRegistry,
@@ -258,7 +268,10 @@ export function createToolbarFactory(
258
268
  pluginId: string,
259
269
  translator: ITranslator,
260
270
  propertyId: string = 'toolbar'
261
- ): (widget: Widget) => IObservableList<ToolbarRegistry.IToolbarItem> {
271
+ ): (
272
+ widget: Widget,
273
+ commandArgs?: PartialJSONObject
274
+ ) => IObservableList<ToolbarRegistry.IToolbarItem> {
262
275
  const items = new ObservableList<ISettingRegistry.IToolbarItem>({
263
276
  itemCmp: (a, b) =>
264
277
  JSONExt.deepEqual(a as PartialJSONObject, b as PartialJSONObject)
@@ -279,7 +292,14 @@ export function createToolbarFactory(
279
292
  );
280
293
  });
281
294
 
282
- return (widget: Widget) => {
295
+ return (widget: Widget, commandArgs?: PartialJSONObject) => {
296
+ const createWidget = (item: ToolbarRegistry.IWidget) =>
297
+ toolbarRegistry.createWidget(
298
+ factoryName,
299
+ widget,
300
+ commandArgs ? { ...item, args: { ...commandArgs, ...item.args } } : item
301
+ );
302
+
283
303
  const updateToolbar = (
284
304
  list: IObservableList<ToolbarRegistry.IWidget>,
285
305
  change: IObservableList.IChangedArgs<ToolbarRegistry.IWidget>
@@ -292,7 +312,7 @@ export function createToolbarFactory(
292
312
  change.newValues.forEach(item =>
293
313
  toolbar.push({
294
314
  name: item.name,
295
- widget: toolbarRegistry.createWidget(factoryName, widget, item)
315
+ widget: createWidget(item)
296
316
  })
297
317
  );
298
318
  break;
@@ -303,7 +323,7 @@ export function createToolbarFactory(
303
323
  change.newValues.forEach(item =>
304
324
  toolbar.set(change.newIndex, {
305
325
  name: item.name,
306
- widget: toolbarRegistry.createWidget(factoryName, widget, item)
326
+ widget: createWidget(item)
307
327
  })
308
328
  );
309
329
  break;
@@ -323,11 +343,7 @@ export function createToolbarFactory(
323
343
  if (itemIndex >= 0) {
324
344
  toolbar.set(itemIndex, {
325
345
  name: itemName,
326
- widget: toolbarRegistry.createWidget(
327
- factoryName,
328
- widget,
329
- items.get(itemIndex)
330
- )
346
+ widget: createWidget(items.get(itemIndex))
331
347
  });
332
348
  }
333
349
  };
@@ -336,7 +352,7 @@ export function createToolbarFactory(
336
352
  values: Array.from(items).map(item => {
337
353
  return {
338
354
  name: item.name,
339
- widget: toolbarRegistry.createWidget(factoryName, widget, item)
355
+ widget: createWidget(item)
340
356
  };
341
357
  })
342
358
  });
@@ -220,6 +220,37 @@
220
220
  flex: 0 0 auto;
221
221
  }
222
222
 
223
+ .lm-CommandPalette-itemContent.jp-mod-recent {
224
+ display: flex;
225
+ }
226
+
227
+ .lm-CommandPalette-itemContent.jp-mod-recent .lm-CommandPalette-itemLabel {
228
+ flex: 1 1 auto;
229
+ }
230
+
231
+ .jp-CommandPalette-recentBadge {
232
+ flex: 0 0 auto;
233
+ align-self: center;
234
+ padding: 0 4px;
235
+ color: var(--jp-brand-color1);
236
+ font-size: var(--jp-ui-font-size0);
237
+ }
238
+
239
+ /*
240
+ * The brand color lacks contrast on the hover background.
241
+ */
242
+ .lm-CommandPalette-item:hover .jp-CommandPalette-recentBadge {
243
+ color: var(--jp-ui-font-color1);
244
+ }
245
+
246
+ .lm-CommandPalette-item.lm-mod-disabled .jp-CommandPalette-recentBadge {
247
+ color: var(--jp-ui-font-color2);
248
+ }
249
+
250
+ .lm-CommandPalette-item.lm-mod-active .jp-CommandPalette-recentBadge {
251
+ color: var(--jp-ui-inverse-font-color1);
252
+ }
253
+
223
254
  .lm-CommandPalette-itemCaption {
224
255
  display: none;
225
256
  }