@jupyterlab/apputils-extension 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.
@@ -14,11 +14,13 @@ import {
14
14
  } from '@jupyterlab/apputils';
15
15
  import { IStateDB } from '@jupyterlab/statedb';
16
16
  import { ITranslator } from '@jupyterlab/translation';
17
+ import { AccordionPanelReorderer } from '@jupyterlab/ui-components';
17
18
  import type {
18
19
  ReadonlyPartialJSONObject,
19
20
  ReadonlyPartialJSONValue
20
21
  } from '@lumino/coreutils';
21
- import type { AccordionLayout, AccordionPanel, Widget } from '@lumino/widgets';
22
+ import { JSONExt } from '@lumino/coreutils';
23
+ import type { AccordionPanel, Widget } from '@lumino/widgets';
22
24
 
23
25
  /**
24
26
  * State DB key for persisting moved sections.
@@ -43,6 +45,9 @@ interface IMoveSectionsState {
43
45
  namespace CommandIDs {
44
46
  export const moveSectionTo = 'apputils:move-section-to';
45
47
  export const moveSectionBack = 'apputils:move-section-back';
48
+ export const toggleSectionReordering = 'apputils:toggle-section-reordering';
49
+ export const moveSectionUp = 'apputils:move-section-up';
50
+ export const moveSectionDown = 'apputils:move-section-down';
46
51
  }
47
52
 
48
53
  /**
@@ -63,12 +68,113 @@ export const moveSectionsPlugin: JupyterFrontEndPlugin<void> = {
63
68
  registry: IMovableSectionRegistry | null,
64
69
  stateDB: IStateDB | null
65
70
  ): void => {
71
+ const trans = translator.load('jupyterlab');
72
+
73
+ const contextReorderer = (): AccordionPanelReorderer | undefined => {
74
+ const node = app.contextMenuHitTest(node =>
75
+ node.classList.contains('lm-AccordionPanel')
76
+ );
77
+ return node ? AccordionPanelReorderer.find(node) : undefined;
78
+ };
79
+
80
+ app.commands.addCommand(CommandIDs.toggleSectionReordering, {
81
+ label: trans.__('Enable Section Reordering'),
82
+ describedBy: { args: { type: 'object', properties: {} } },
83
+ isVisible: () => contextReorderer() !== undefined,
84
+ isToggled: () => AccordionPanelReorderer.enabled,
85
+ execute: () => {
86
+ AccordionPanelReorderer.enabled = !AccordionPanelReorderer.enabled;
87
+ }
88
+ });
89
+ app.contextMenu.addItem({
90
+ command: CommandIDs.toggleSectionReordering,
91
+ selector: '.lm-AccordionPanel-title',
92
+ rank: 20
93
+ });
94
+
95
+ /**
96
+ * The section to move: from a key binding, the one whose header has the
97
+ * focus; otherwise, the one whose header was right-clicked.
98
+ */
99
+ const targetSection = (
100
+ args: ReadonlyPartialJSONObject
101
+ ): { reorderer: AccordionPanelReorderer; index: number } | undefined => {
102
+ const event = args._luminoEvent;
103
+ const fromKeyBinding =
104
+ event !== undefined &&
105
+ JSONExt.isObject(event) &&
106
+ event.type === 'keybinding';
107
+ const title = fromKeyBinding
108
+ ? document.activeElement?.closest<HTMLElement>(
109
+ '.lm-AccordionPanel-title'
110
+ )
111
+ : app.contextMenuHitTest(node =>
112
+ node.classList.contains('lm-AccordionPanel-title')
113
+ );
114
+ const panelNode = title?.parentElement;
115
+ const reorderer = panelNode
116
+ ? AccordionPanelReorderer.find(panelNode)
117
+ : undefined;
118
+ if (!title || !reorderer) {
119
+ return undefined;
120
+ }
121
+ const index = reorderer.panel.titles.indexOf(title);
122
+ return index < 0 ? undefined : { reorderer, index };
123
+ };
124
+
125
+ const addMoveCommand = (id: string, label: string, offset: -1 | 1) => {
126
+ /**
127
+ * The section index to move from and to, if reordering is unlocked and
128
+ * the section is not already at that end of the panel.
129
+ */
130
+ const resolveMove = (args: ReadonlyPartialJSONObject) => {
131
+ const section = AccordionPanelReorderer.enabled
132
+ ? targetSection(args)
133
+ : undefined;
134
+ if (!section) {
135
+ return undefined;
136
+ }
137
+ const { reorderer, index: from } = section;
138
+ const to = from + offset;
139
+ return to >= 0 && to < reorderer.panel.widgets.length
140
+ ? { reorderer, from, to }
141
+ : undefined;
142
+ };
143
+ app.commands.addCommand(id, {
144
+ label,
145
+ describedBy: { args: { type: 'object', properties: {} } },
146
+ isVisible: args =>
147
+ AccordionPanelReorderer.enabled && targetSection(args) !== undefined,
148
+ isEnabled: args => resolveMove(args) !== undefined,
149
+ execute: args => {
150
+ const move = resolveMove(args);
151
+ if (!move) {
152
+ return;
153
+ }
154
+ const { reorderer, from, to } = move;
155
+ reorderer.move(reorderer.panel.widgets[from], to);
156
+ // Moving the header in the DOM, or choosing a menu item, takes the
157
+ // focus away from it.
158
+ reorderer.panel.titles[to].focus();
159
+ }
160
+ });
161
+ app.contextMenu.addItem({
162
+ command: id,
163
+ selector: '.lm-AccordionPanel-title',
164
+ rank: 21
165
+ });
166
+ };
167
+ addMoveCommand(CommandIDs.moveSectionUp, trans.__('Move Section Up'), -1);
168
+ addMoveCommand(
169
+ CommandIDs.moveSectionDown,
170
+ trans.__('Move Section Down'),
171
+ 1
172
+ );
173
+
66
174
  if (!registry) {
67
175
  return;
68
176
  }
69
177
 
70
- const trans = translator.load('jupyterlab');
71
-
72
178
  // section title element (in source sidebar) → section identity
73
179
  const titleToSection = new WeakMap<
74
180
  HTMLElement,
@@ -149,130 +255,15 @@ export const moveSectionsPlugin: JupyterFrontEndPlugin<void> = {
149
255
  );
150
256
  };
151
257
 
152
- // Re-appending all titles in logical to fix keyboard Tab navigation.
153
- const syncTitleDOMOrder = (accordion: AccordionPanel): void => {
154
- const layout = accordion.layout as AccordionLayout;
155
- for (const title of layout.titles) {
156
- accordion.node.appendChild(title);
157
- }
158
- };
159
-
160
- const addDragHandle = (widget: Widget, accordion: AccordionPanel): void => {
161
- const idx = Array.from(accordion.widgets).indexOf(widget);
162
- if (idx < 0) {
163
- return;
164
- }
165
- const titleEl = accordion.titles[idx];
166
- if (!titleEl.querySelector('.jp-movable-section-dragHandle')) {
167
- const handle = document.createElement('span');
168
- handle.className = 'jp-movable-section-dragHandle';
169
- titleEl.prepend(handle);
170
- }
171
- };
172
-
173
258
  const setupAccordionDrag = (accordion: AccordionPanel): void => {
174
259
  if (dragSetupDone.has(accordion)) {
175
260
  return;
176
261
  }
177
262
  dragSetupDone.add(accordion);
178
-
179
- // Persist collapse/expand state whenever the user toggles a section.
180
263
  accordion.expansionToggled.connect(() => void saveState());
181
-
182
- let draggedWidget: Widget | null = null;
183
- let startY = 0;
184
- let isDragging = false;
185
-
186
- const indicator = document.createElement('div');
187
- indicator.className = 'jp-movable-section-dropIndicator';
188
- indicator.style.display = 'none';
189
- accordion.node.appendChild(indicator);
190
-
191
- const getTargetSlot = (clientY: number): number => {
192
- const layout = accordion.layout as AccordionLayout;
193
- const titles = Array.from(layout.titles);
194
- for (let i = 0; i < titles.length; i++) {
195
- const rect = titles[i].getBoundingClientRect();
196
- if (clientY < rect.top + rect.height / 2) {
197
- return i;
198
- }
199
- }
200
- return titles.length;
201
- };
202
-
203
- const showIndicator = (targetSlot: number): void => {
204
- const layout = accordion.layout as AccordionLayout;
205
- const titles = Array.from(layout.titles);
206
- const panelRect = accordion.node.getBoundingClientRect();
207
- let top: number;
208
- if (targetSlot < titles.length) {
209
- top = titles[targetSlot].getBoundingClientRect().top - panelRect.top;
210
- } else {
211
- const last = titles[titles.length - 1].getBoundingClientRect();
212
- top = last.bottom - panelRect.top;
213
- }
214
- indicator.style.top = `${top}px`;
215
- indicator.style.display = 'block';
216
- };
217
-
218
- const endDrag = (clientY?: number): void => {
219
- indicator.style.display = 'none';
220
- accordion.node.classList.remove('jp-mod-dragging');
221
- if (isDragging && draggedWidget && clientY !== undefined) {
222
- const currentIdx = Array.from(accordion.widgets).indexOf(
223
- draggedWidget
224
- );
225
- const targetSlot = getTargetSlot(clientY);
226
- const insertIdx =
227
- targetSlot > currentIdx ? targetSlot - 1 : targetSlot;
228
- if (insertIdx !== currentIdx) {
229
- accordion.insertWidget(insertIdx, draggedWidget);
230
- syncTitleDOMOrder(accordion);
231
- void saveState();
232
- }
233
- }
234
- draggedWidget = null;
235
- isDragging = false;
236
- };
237
-
238
- accordion.node.addEventListener('pointerdown', (event: PointerEvent) => {
239
- const target = event.target as HTMLElement;
240
- const titleEl = target.closest(
241
- '.jp-AccordionPanel-title'
242
- ) as HTMLElement | null;
243
- if (!titleEl || !target.closest('.jp-movable-section-dragHandle')) {
244
- return;
245
- }
246
- const layout = accordion.layout as AccordionLayout;
247
- const idx = Array.from(layout.titles).indexOf(titleEl);
248
- if (idx < 0) {
249
- return;
250
- }
251
- draggedWidget = accordion.widgets[idx];
252
- startY = event.clientY;
253
- accordion.node.setPointerCapture(event.pointerId);
254
- });
255
-
256
- accordion.node.addEventListener('pointermove', (event: PointerEvent) => {
257
- if (!draggedWidget) {
258
- return;
259
- }
260
- if (!isDragging && Math.abs(event.clientY - startY) > 5) {
261
- isDragging = true;
262
- accordion.node.classList.add('jp-mod-dragging');
263
- }
264
- if (isDragging) {
265
- showIndicator(getTargetSlot(event.clientY));
266
- }
267
- });
268
-
269
- accordion.node.addEventListener('pointerup', (event: PointerEvent) => {
270
- endDrag(event.clientY);
271
- });
272
-
273
- accordion.node.addEventListener('pointercancel', () => {
274
- endDrag();
275
- });
264
+ AccordionPanelReorderer.get(accordion, translator).reordered.connect(
265
+ () => void saveState()
266
+ );
276
267
  };
277
268
 
278
269
  // Core move operations
@@ -300,12 +291,20 @@ export const moveSectionsPlugin: JupyterFrontEndPlugin<void> = {
300
291
  const target = Math.max(0, Math.min(index, total - 1));
301
292
  if (accordion.widgets[target] !== widget) {
302
293
  accordion.insertWidget(target, widget);
303
- syncTitleDOMOrder(accordion);
294
+ // Lumino only repositions the section, so move its title, body
295
+ // and handle to keep the Tab order the same as the visual order.
296
+ const next = accordion.titles[target + 1] ?? null;
297
+ for (const node of [
298
+ accordion.titles[target],
299
+ widget.node,
300
+ accordion.handles[target]
301
+ ]) {
302
+ accordion.node.insertBefore(node, next);
303
+ }
304
304
  }
305
305
  }
306
306
 
307
307
  setupAccordionDrag(accordion);
308
- addDragHandle(widget, accordion);
309
308
 
310
309
  const idx = Array.from(accordion.widgets).indexOf(widget);
311
310
  if (idx >= 0) {
@@ -440,7 +439,7 @@ export const moveSectionsPlugin: JupyterFrontEndPlugin<void> = {
440
439
  rank: 10
441
440
  });
442
441
 
443
- if (panel.accordionPanel && panel.sections.length > 0) {
442
+ if (panel.accordionPanel) {
444
443
  setupAccordionDrag(panel.accordionPanel);
445
444
  }
446
445
  };
package/src/palette.ts CHANGED
@@ -5,26 +5,39 @@
5
5
 
6
6
  import type { ILayoutRestorer, JupyterFrontEnd } from '@jupyterlab/application';
7
7
  import type { ICommandPalette, IPaletteItem } from '@jupyterlab/apputils';
8
- import { ModalCommandPalette } from '@jupyterlab/apputils';
8
+ import {
9
+ ModalCommandPalette,
10
+ RecentsCommandPalette
11
+ } from '@jupyterlab/apputils';
9
12
  import type { ISettingRegistry } from '@jupyterlab/settingregistry';
10
- import type { ITranslator } from '@jupyterlab/translation';
13
+ import type { IStateDB } from '@jupyterlab/statedb';
14
+ import type { ITranslator, TranslationBundle } from '@jupyterlab/translation';
11
15
  import { nullTranslator } from '@jupyterlab/translation';
12
16
  import { CommandPaletteSvg, paletteIcon } from '@jupyterlab/ui-components';
13
17
  import { find } from '@lumino/algorithm';
14
18
  import { CommandRegistry } from '@lumino/commands';
15
19
  import type { IDisposable } from '@lumino/disposable';
16
20
  import { DisposableDelegate } from '@lumino/disposable';
17
- import { CommandPalette } from '@lumino/widgets';
21
+ import type { VirtualElement } from '@lumino/virtualdom';
22
+ import { h } from '@lumino/virtualdom';
23
+ import type { CommandPalette } from '@lumino/widgets';
18
24
 
19
25
  /**
20
26
  * The command IDs used by the apputils extension.
21
27
  */
22
28
  namespace CommandIDs {
23
29
  export const activate = 'apputils:activate-command-palette';
30
+
31
+ export const clearRecents = 'apputils:clear-recent-commands';
24
32
  }
25
33
 
26
34
  const PALETTE_PLUGIN_ID = '@jupyterlab/apputils-extension:palette';
27
35
 
36
+ /**
37
+ * The state database key of the recent commands.
38
+ */
39
+ const RECENTS_STATE_KEY = 'command-palette:recents';
40
+
28
41
  /**
29
42
  * A thin wrapper around the `CommandPalette` class to conform with the
30
43
  * JupyterLab interface for the application-wide command palette.
@@ -94,7 +107,7 @@ export namespace Palette {
94
107
  ): ICommandPalette {
95
108
  const { commands, shell } = app;
96
109
  const trans = translator.load('jupyterlab');
97
- const palette = Private.createPalette(app);
110
+ const palette = Private.createPalette(app, translator);
98
111
  const modalPalette = new ModalCommandPalette({
99
112
  commandPalette: palette,
100
113
  restore: () => {
@@ -128,6 +141,8 @@ export namespace Palette {
128
141
  modalPalette.attach();
129
142
  }
130
143
  modal = newModal;
144
+ palette.maxRecentCommands = settings.get('maxRecentCommands')
145
+ .composite as number;
131
146
  };
132
147
 
133
148
  Promise.all([loadSettings, app.restored])
@@ -177,6 +192,30 @@ export namespace Palette {
177
192
  label: trans.__('Activate Command Palette')
178
193
  });
179
194
 
195
+ commands.addCommand(CommandIDs.clearRecents, {
196
+ describedBy: {
197
+ args: {
198
+ type: 'object',
199
+ properties: {}
200
+ }
201
+ },
202
+ execute: () => {
203
+ palette.recentCommands = [];
204
+ },
205
+ isEnabled: () => palette.recentCommands.length > 0,
206
+ label: trans.__('Clear Recently Used Commands'),
207
+ caption: trans.__('Clear the list of recently used commands.')
208
+ });
209
+ palette.addItem({
210
+ command: CommandIDs.clearRecents,
211
+ category: trans.__('Command Palette')
212
+ });
213
+
214
+ // Keep the enabled state of the clear command up to date.
215
+ palette.recentsChanged.connect(() => {
216
+ commands.notifyCommandChanged(CommandIDs.clearRecents);
217
+ });
218
+
180
219
  palette.inputNode.placeholder = trans.__('SEARCH');
181
220
 
182
221
  return new Palette(palette, translator);
@@ -187,13 +226,57 @@ export namespace Palette {
187
226
  */
188
227
  export function restore(
189
228
  app: JupyterFrontEnd,
190
- restorer: ILayoutRestorer
229
+ restorer: ILayoutRestorer,
230
+ translator: ITranslator,
231
+ state: IStateDB,
232
+ settingRegistry: ISettingRegistry | null
191
233
  ): void {
192
- const palette = Private.createPalette(app);
234
+ const palette = Private.createPalette(app, translator);
193
235
  // Let the application restorer track the command palette for restoration of
194
236
  // application state (e.g. setting the command palette as the current side bar
195
237
  // widget).
196
238
  restorer.add(palette, 'command-palette');
239
+
240
+ // Apply the limit first, so that the default limit does not truncate the
241
+ // restored history.
242
+ const limitApplied = settingRegistry
243
+ ? settingRegistry.load(PALETTE_PLUGIN_ID).then(settings => {
244
+ palette.maxRecentCommands = settings.get('maxRecentCommands')
245
+ .composite as number;
246
+ })
247
+ : Promise.resolve();
248
+ const restored = limitApplied
249
+ .then(() => state.fetch(RECENTS_STATE_KEY))
250
+ .then(async value => {
251
+ const saved = (
252
+ value as
253
+ | { commands?: RecentsCommandPalette.IRecentCommand[] }
254
+ | undefined
255
+ )?.commands;
256
+ if (!Array.isArray(saved)) {
257
+ return;
258
+ }
259
+ if (palette.maxRecentCommands === 0) {
260
+ await state.remove(RECENTS_STATE_KEY);
261
+ } else {
262
+ palette.recentCommands = [...palette.recentCommands, ...saved];
263
+ }
264
+ })
265
+ .catch((reason: Error) => {
266
+ console.error('Failed to restore the recently used commands.', reason);
267
+ });
268
+
269
+ // Wait for the restoration, so that an early save does not overwrite
270
+ // the stored history.
271
+ palette.recentsChanged.connect(() => {
272
+ void restored
273
+ .then(() =>
274
+ state.save(RECENTS_STATE_KEY, { commands: palette.recentCommands })
275
+ )
276
+ .catch((reason: Error) => {
277
+ console.warn('Failed to save the recently used commands.', reason);
278
+ });
279
+ });
197
280
  }
198
281
  }
199
282
 
@@ -204,17 +287,59 @@ namespace Private {
204
287
  /**
205
288
  * The private command palette instance.
206
289
  */
207
- let palette: CommandPalette;
290
+ let palette: RecentsCommandPalette;
291
+
292
+ /**
293
+ * A command palette renderer which adds a badge to the recent commands.
294
+ */
295
+ class Renderer extends CommandPaletteSvg.Renderer {
296
+ /**
297
+ * Construct a new renderer.
298
+ */
299
+ constructor(
300
+ translator: ITranslator,
301
+ isRecent: (item: CommandPalette.IItem) => boolean
302
+ ) {
303
+ super();
304
+ this._isRecent = isRecent;
305
+ this._trans = translator.load('jupyterlab');
306
+ }
307
+
308
+ /**
309
+ * Render the content for a command palette item.
310
+ */
311
+ renderItemContent(data: CommandPalette.IItemRenderData): VirtualElement {
312
+ if (!this._isRecent(data.item)) {
313
+ return super.renderItemContent(data);
314
+ }
315
+ return h.div(
316
+ { className: 'lm-CommandPalette-itemContent jp-mod-recent' },
317
+ this.renderItemLabel(data),
318
+ this.renderItemCaption(data),
319
+ h.div(
320
+ { className: 'jp-CommandPalette-recentBadge' },
321
+ this._trans.__('recently used')
322
+ )
323
+ );
324
+ }
325
+
326
+ private _isRecent: (item: CommandPalette.IItem) => boolean;
327
+ private _trans: TranslationBundle;
328
+ }
208
329
 
209
330
  /**
210
331
  * Create the application-wide command palette.
211
332
  */
212
- export function createPalette(app: JupyterFrontEnd): CommandPalette {
333
+ export function createPalette(
334
+ app: JupyterFrontEnd,
335
+ translator: ITranslator
336
+ ): RecentsCommandPalette {
213
337
  if (!palette) {
214
- // use a renderer tweaked to use inline svg icons
215
- palette = new CommandPalette({
338
+ // use a renderer tweaked to use inline svg icons and to display a
339
+ // badge for the recent commands
340
+ palette = new RecentsCommandPalette({
216
341
  commands: app.commands,
217
- renderer: CommandPaletteSvg.defaultRenderer
342
+ renderer: new Renderer(translator, item => palette.isRecent(item))
218
343
  });
219
344
  palette.id = 'command-palette';
220
345
  palette.title.icon = paletteIcon;