@jupyterlab/cells 4.0.0-alpha.9 → 4.0.0-beta.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.
@@ -0,0 +1,125 @@
1
+ /* -----------------------------------------------------------------------------
2
+ | Copyright (c) Jupyter Development Team.
3
+ | Distributed under the terms of the Modified BSD License.
4
+ |----------------------------------------------------------------------------*/
5
+
6
+ import { ellipsesIcon } from '@jupyterlab/ui-components';
7
+ import { Widget } from '@lumino/widgets';
8
+ import { Message } from '@lumino/messaging';
9
+
10
+ /**
11
+ * The CSS class added to placeholders.
12
+ */
13
+ const PLACEHOLDER_CLASS = 'jp-Placeholder';
14
+
15
+ /**
16
+ * The CSS classes added to input placeholder prompts.
17
+ */
18
+ const INPUT_PROMPT_CLASS = 'jp-Placeholder-prompt jp-InputPrompt';
19
+
20
+ /**
21
+ * The CSS classes added to output placeholder prompts.
22
+ */
23
+ const OUTPUT_PROMPT_CLASS = 'jp-Placeholder-prompt jp-OutputPrompt';
24
+
25
+ /**
26
+ * The CSS class added to placeholder content.
27
+ */
28
+ const CONTENT_CLASS = 'jp-Placeholder-content';
29
+
30
+ /**
31
+ * The CSS class added to input placeholders.
32
+ */
33
+ const INPUT_PLACEHOLDER_CLASS = 'jp-InputPlaceholder';
34
+
35
+ /**
36
+ * The CSS class added to output placeholders.
37
+ */
38
+ const OUTPUT_PLACEHOLDER_CLASS = 'jp-OutputPlaceholder';
39
+
40
+ /**
41
+ * Placeholder widget options
42
+ */
43
+ export interface IPlaceholderOptions {
44
+ /**
45
+ * Prompt element CSS class
46
+ */
47
+ promptClass: string;
48
+ /**
49
+ * Ellipsis button callback
50
+ */
51
+ callback: (e: MouseEvent) => void;
52
+ }
53
+
54
+ /**
55
+ * An base class for placeholders
56
+ *
57
+ * ### Notes
58
+ * A placeholder is the element that is shown when input/output
59
+ * is hidden.
60
+ */
61
+ export class Placeholder extends Widget {
62
+ /**
63
+ * Construct a new placeholder.
64
+ */
65
+ constructor(options: IPlaceholderOptions) {
66
+ const node = document.createElement('div');
67
+
68
+ super({ node });
69
+ const innerNode = document.createElement('div');
70
+ innerNode.className = options.promptClass;
71
+ node.insertAdjacentHTML('afterbegin', innerNode.outerHTML);
72
+ this._button = document.createElement('div');
73
+ this._button.classList.add(CONTENT_CLASS);
74
+ node.appendChild(this._button);
75
+ ellipsesIcon.element({
76
+ container: this._button.appendChild(document.createElement('div')),
77
+ className: 'jp-MoreHorizIcon',
78
+ elementPosition: 'center',
79
+ height: 'auto',
80
+ width: '32px'
81
+ });
82
+
83
+ this.addClass(PLACEHOLDER_CLASS);
84
+ this._callback = options.callback;
85
+ }
86
+
87
+ protected onAfterAttach(msg: Message): void {
88
+ super.onAfterAttach(msg);
89
+ this._button.addEventListener('click', this._callback);
90
+ }
91
+
92
+ protected onBeforeDetach(msg: Message): void {
93
+ this._button.removeEventListener('click', this._callback);
94
+ super.onBeforeDetach(msg);
95
+ }
96
+
97
+ private _callback: (e: MouseEvent) => void;
98
+ private _button: HTMLElement;
99
+ }
100
+
101
+ /**
102
+ * The input placeholder class.
103
+ */
104
+ export class InputPlaceholder extends Placeholder {
105
+ /**
106
+ * Construct a new input placeholder.
107
+ */
108
+ constructor(callback: (e: MouseEvent) => void) {
109
+ super({ callback, promptClass: INPUT_PROMPT_CLASS });
110
+ this.addClass(INPUT_PLACEHOLDER_CLASS);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * The output placeholder class.
116
+ */
117
+ export class OutputPlaceholder extends Placeholder {
118
+ /**
119
+ * Construct a new output placeholder.
120
+ */
121
+ constructor(callback: (e: MouseEvent) => void) {
122
+ super({ callback, promptClass: OUTPUT_PROMPT_CLASS });
123
+ this.addClass(OUTPUT_PLACEHOLDER_CLASS);
124
+ }
125
+ }
@@ -0,0 +1,96 @@
1
+ /*
2
+ * Copyright (c) Jupyter Development Team.
3
+ * Distributed under the terms of the Modified BSD License.
4
+ */
5
+
6
+ import { Widget } from '@lumino/widgets';
7
+ import { Message } from '@lumino/messaging';
8
+
9
+ const RESIZE_HANDLE_CLASS = 'jp-CellResizeHandle';
10
+
11
+ const CELL_RESIZED_CLASS = 'jp-mod-resizedCell';
12
+
13
+ /**
14
+ * A handle that allows to change input/output proportions in side-by-side mode.
15
+ */
16
+ export class ResizeHandle extends Widget {
17
+ private _isActive: boolean = false;
18
+ private _isDragging: boolean = false;
19
+ private _protectedWidth = 10;
20
+
21
+ constructor(protected targetNode: HTMLElement) {
22
+ super();
23
+ this.addClass(RESIZE_HANDLE_CLASS);
24
+ }
25
+
26
+ protected onAfterAttach(msg: Message) {
27
+ super.onAfterAttach(msg);
28
+ this.node.addEventListener('dblclick', this);
29
+ this.node.addEventListener('mousedown', this);
30
+ }
31
+
32
+ protected onAfterDetach(msg: Message) {
33
+ super.onAfterAttach(msg);
34
+ this.node.removeEventListener('dblclick', this);
35
+ this.node.removeEventListener('mousedown', this);
36
+ }
37
+
38
+ /**
39
+ * Handle the DOM events for the widget.
40
+ *
41
+ * @param event - The DOM event sent to the widget.
42
+ *
43
+ */
44
+ handleEvent(event: Event): void {
45
+ switch (event.type) {
46
+ case 'dblclick':
47
+ this.targetNode.parentNode?.childNodes.forEach(node => {
48
+ (node as HTMLElement).classList.remove(CELL_RESIZED_CLASS);
49
+ });
50
+ document.documentElement.style.setProperty(
51
+ '--jp-side-by-side-output-size',
52
+ `1fr`
53
+ );
54
+ this._isActive = false;
55
+ break;
56
+ case 'mousedown':
57
+ this._isDragging = true;
58
+ if (!this._isActive) {
59
+ this.targetNode.parentNode?.childNodes.forEach(node => {
60
+ (node as HTMLElement).classList.add(CELL_RESIZED_CLASS);
61
+ });
62
+
63
+ this._isActive = true;
64
+ }
65
+ window.addEventListener('mousemove', this);
66
+ window.addEventListener('mouseup', this);
67
+ break;
68
+ case 'mousemove': {
69
+ if (!this._isActive || !this._isDragging) {
70
+ return;
71
+ }
72
+ const targetRect = this.targetNode.getBoundingClientRect();
73
+
74
+ const width = targetRect.width - this._protectedWidth * 2;
75
+ const position =
76
+ (event as MouseEvent).clientX - targetRect.x - this._protectedWidth;
77
+
78
+ const outputRatio = width / position - 1;
79
+
80
+ document.documentElement.style.setProperty(
81
+ '--jp-side-by-side-output-size',
82
+ `${outputRatio}fr`
83
+ );
84
+
85
+ break;
86
+ }
87
+ case 'mouseup':
88
+ this._isDragging = false;
89
+ window.removeEventListener('mousemove', this);
90
+ window.removeEventListener('mouseup', this);
91
+ break;
92
+ default:
93
+ break;
94
+ }
95
+ }
96
+ }
@@ -0,0 +1,436 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { CodeEditor } from '@jupyterlab/codeeditor';
5
+ import { CodeMirrorEditor, EditorSearchProvider } from '@jupyterlab/codemirror';
6
+ import { signalToPromise } from '@jupyterlab/coreutils';
7
+ import {
8
+ GenericSearchProvider,
9
+ IBaseSearchProvider,
10
+ IFilters,
11
+ ISearchMatch
12
+ } from '@jupyterlab/documentsearch';
13
+ import { OutputArea } from '@jupyterlab/outputarea';
14
+ import { ICellModel } from './model';
15
+ import { Cell, CodeCell, MarkdownCell } from './widget';
16
+
17
+ /**
18
+ * Class applied on highlighted search matches
19
+ */
20
+ export const SELECTED_HIGHLIGHT_CLASS = 'jp-mod-selected';
21
+
22
+ /**
23
+ * Search provider for cells.
24
+ */
25
+ export class CellSearchProvider
26
+ extends EditorSearchProvider<ICellModel>
27
+ implements IBaseSearchProvider
28
+ {
29
+ constructor(protected cell: Cell<ICellModel>) {
30
+ super();
31
+ if (!this.cell.inViewport && !this.cell.editor) {
32
+ void signalToPromise(cell.inViewportChanged).then(([, inViewport]) => {
33
+ if (inViewport) {
34
+ this.cmHandler.setEditor(this.editor as CodeMirrorEditor);
35
+ }
36
+ });
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Text editor
42
+ */
43
+ protected get editor(): CodeEditor.IEditor | null {
44
+ return this.cell.editor;
45
+ }
46
+
47
+ /**
48
+ * Editor content model
49
+ */
50
+ protected get model() {
51
+ return this.cell.model;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Code cell search provider
57
+ */
58
+ class CodeCellSearchProvider extends CellSearchProvider {
59
+ /**
60
+ * Constructor
61
+ *
62
+ * @param cell Cell widget
63
+ */
64
+ constructor(cell: Cell<ICellModel>) {
65
+ super(cell);
66
+
67
+ this.currentProviderIndex = -1;
68
+ this.outputsProvider = [];
69
+
70
+ const outputs = (this.cell as CodeCell).outputArea;
71
+ this._onOutputsChanged(outputs, outputs.widgets.length).catch(reason => {
72
+ console.error(`Failed to initialize search on cell outputs.`, reason);
73
+ });
74
+ outputs.outputLengthChanged.connect(this._onOutputsChanged, this);
75
+ outputs.disposed.connect(() => {
76
+ outputs.outputLengthChanged.disconnect(this._onOutputsChanged);
77
+ }, this);
78
+ }
79
+
80
+ /**
81
+ * Number of matches in the cell.
82
+ */
83
+ get matchesCount(): number {
84
+ if (!this.isActive) {
85
+ return 0;
86
+ }
87
+
88
+ return (
89
+ super.matchesCount +
90
+ this.outputsProvider.reduce(
91
+ (sum, provider) => sum + (provider.matchesCount ?? 0),
92
+ 0
93
+ )
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Clear currently highlighted match.
99
+ */
100
+ async clearHighlight(): Promise<void> {
101
+ await super.clearHighlight();
102
+ await Promise.all(
103
+ this.outputsProvider.map(provider => provider.clearHighlight())
104
+ );
105
+ }
106
+
107
+ /**
108
+ * Dispose the search provider
109
+ */
110
+ dispose(): void {
111
+ if (this.isDisposed) {
112
+ return;
113
+ }
114
+ super.dispose();
115
+ this.outputsProvider.map(provider => {
116
+ provider.dispose();
117
+ });
118
+ this.outputsProvider.length = 0;
119
+ }
120
+
121
+ /**
122
+ * Highlight the next match.
123
+ *
124
+ * @returns The next match if there is one.
125
+ */
126
+ async highlightNext(
127
+ loop?: boolean,
128
+ fromCursor = false
129
+ ): Promise<ISearchMatch | undefined> {
130
+ if (this.matchesCount === 0 || !this.isActive) {
131
+ this.currentIndex = null;
132
+ } else {
133
+ if (this.currentProviderIndex === -1) {
134
+ const match = await super.highlightNext(true, fromCursor);
135
+ if (match) {
136
+ this.currentIndex = this.cmHandler.currentIndex;
137
+ return match;
138
+ } else {
139
+ this.currentProviderIndex = 0;
140
+ }
141
+ }
142
+
143
+ while (this.currentProviderIndex < this.outputsProvider.length) {
144
+ const provider = this.outputsProvider[this.currentProviderIndex];
145
+ const match = await provider.highlightNext(false);
146
+ if (match) {
147
+ this.currentIndex =
148
+ super.matchesCount +
149
+ this.outputsProvider
150
+ .slice(0, this.currentProviderIndex)
151
+ .reduce(
152
+ (sum, provider) => (sum += provider.matchesCount ?? 0),
153
+ 0
154
+ ) +
155
+ provider.currentMatchIndex!;
156
+ return match;
157
+ } else {
158
+ this.currentProviderIndex += 1;
159
+ }
160
+ }
161
+
162
+ this.currentProviderIndex = -1;
163
+ this.currentIndex = null;
164
+ return undefined;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Highlight the previous match.
170
+ *
171
+ * @returns The previous match if there is one.
172
+ */
173
+ async highlightPrevious(): Promise<ISearchMatch | undefined> {
174
+ if (this.matchesCount === 0 || !this.isActive) {
175
+ this.currentIndex = null;
176
+ } else {
177
+ if (this.currentIndex === null) {
178
+ this.currentProviderIndex = this.outputsProvider.length - 1;
179
+ }
180
+
181
+ while (this.currentProviderIndex >= 0) {
182
+ const provider = this.outputsProvider[this.currentProviderIndex];
183
+
184
+ const match = await provider.highlightPrevious(false);
185
+ if (match) {
186
+ this.currentIndex =
187
+ super.matchesCount +
188
+ this.outputsProvider
189
+ .slice(0, this.currentProviderIndex)
190
+ .reduce(
191
+ (sum, provider) => (sum += provider.matchesCount ?? 0),
192
+ 0
193
+ ) +
194
+ provider.currentMatchIndex!;
195
+ return match;
196
+ } else {
197
+ this.currentProviderIndex -= 1;
198
+ }
199
+ }
200
+
201
+ const match = await super.highlightPrevious();
202
+ if (match) {
203
+ this.currentIndex = this.cmHandler.currentIndex;
204
+ return match;
205
+ } else {
206
+ this.currentIndex = null;
207
+ return undefined;
208
+ }
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Initialize the search using the provided options. Should update the UI to highlight
214
+ * all matches and "select" the first match.
215
+ *
216
+ * @param query A RegExp to be use to perform the search
217
+ * @param filters Filter parameters to pass to provider
218
+ */
219
+ async startQuery(query: RegExp | null, filters?: IFilters): Promise<void> {
220
+ await super.startQuery(query, filters);
221
+
222
+ // Search outputs
223
+ if (filters?.output !== false && this.isActive) {
224
+ await Promise.all(
225
+ this.outputsProvider.map(provider => provider.startQuery(query))
226
+ );
227
+ }
228
+ }
229
+
230
+ async endQuery(): Promise<void> {
231
+ await super.endQuery();
232
+ if (this.filters?.output !== false && this.isActive) {
233
+ await Promise.all(
234
+ this.outputsProvider.map(provider => provider.endQuery())
235
+ );
236
+ }
237
+ }
238
+
239
+ private async _onOutputsChanged(
240
+ outputArea: OutputArea,
241
+ changes: number
242
+ ): Promise<void> {
243
+ this.outputsProvider.forEach(provider => {
244
+ provider.dispose();
245
+ });
246
+ this.outputsProvider.length = 0;
247
+
248
+ this.currentProviderIndex = -1;
249
+ this.outputsProvider = (this.cell as CodeCell).outputArea.widgets.map(
250
+ output => new GenericSearchProvider(output)
251
+ );
252
+
253
+ if (this.isActive && this.query && this.filters?.output !== false) {
254
+ await Promise.all([
255
+ this.outputsProvider.map(provider => {
256
+ void provider.startQuery(this.query);
257
+ })
258
+ ]);
259
+ }
260
+
261
+ this._stateChanged.emit();
262
+ }
263
+
264
+ protected outputsProvider: GenericSearchProvider[];
265
+ protected currentProviderIndex: number;
266
+ }
267
+
268
+ /**
269
+ * Markdown cell search provider
270
+ */
271
+ class MarkdownCellSearchProvider extends CellSearchProvider {
272
+ /**
273
+ * Constructor
274
+ *
275
+ * @param cell Cell widget
276
+ */
277
+ constructor(cell: Cell<ICellModel>) {
278
+ super(cell);
279
+ this.renderedProvider = new GenericSearchProvider(
280
+ (cell as MarkdownCell).renderer
281
+ );
282
+ }
283
+
284
+ /**
285
+ * Clear currently highlighted match
286
+ */
287
+ async clearHighlight(): Promise<void> {
288
+ await super.clearHighlight();
289
+ await this.renderedProvider.clearHighlight();
290
+ }
291
+
292
+ /**
293
+ * Dispose the search provider
294
+ */
295
+ dispose(): void {
296
+ if (this.isDisposed) {
297
+ return;
298
+ }
299
+ super.dispose();
300
+ this.renderedProvider.dispose();
301
+ }
302
+
303
+ /**
304
+ * Stop the search and clean any UI elements.
305
+ */
306
+ async endQuery(): Promise<void> {
307
+ await super.endQuery();
308
+ await this.renderedProvider.endQuery();
309
+ }
310
+
311
+ /**
312
+ * Highlight the next match.
313
+ *
314
+ * @returns The next match if there is one.
315
+ */
316
+ async highlightNext(): Promise<ISearchMatch | undefined> {
317
+ let match: ISearchMatch | undefined = undefined;
318
+ if (!this.isActive) {
319
+ return match;
320
+ }
321
+
322
+ const cell = this.cell as MarkdownCell;
323
+ if (cell.rendered && this.matchesCount > 0) {
324
+ // Unrender the cell
325
+ this._unrenderedByHighligh = true;
326
+ const waitForRendered = signalToPromise(cell.renderedChanged);
327
+ cell.rendered = false;
328
+ await waitForRendered;
329
+ }
330
+
331
+ match = await super.highlightNext();
332
+
333
+ return match;
334
+ }
335
+
336
+ /**
337
+ * Highlight the previous match.
338
+ *
339
+ * @returns The previous match if there is one.
340
+ */
341
+ async highlightPrevious(): Promise<ISearchMatch | undefined> {
342
+ let match: ISearchMatch | undefined = undefined;
343
+ const cell = this.cell as MarkdownCell;
344
+ if (cell.rendered && this.matchesCount > 0) {
345
+ // Unrender the cell if there are matches within the cell
346
+ this._unrenderedByHighligh = true;
347
+ const waitForRendered = signalToPromise(cell.renderedChanged);
348
+ cell.rendered = false;
349
+ await waitForRendered;
350
+ }
351
+
352
+ match = await super.highlightPrevious();
353
+
354
+ return match;
355
+ }
356
+
357
+ /**
358
+ * Initialize the search using the provided options. Should update the UI
359
+ * to highlight all matches and "select" the first match.
360
+ *
361
+ * @param query A RegExp to be use to perform the search
362
+ * @param filters Filter parameters to pass to provider
363
+ */
364
+ async startQuery(query: RegExp | null, filters?: IFilters): Promise<void> {
365
+ await super.startQuery(query, filters);
366
+ const cell = this.cell as MarkdownCell;
367
+ if (cell.rendered) {
368
+ this.onRenderedChanged(cell, cell.rendered);
369
+ }
370
+ cell.renderedChanged.connect(this.onRenderedChanged, this);
371
+ }
372
+
373
+ /**
374
+ * Replace all matches in the cell source with the provided text
375
+ *
376
+ * @param newText The replacement text.
377
+ * @returns Whether a replace occurred.
378
+ */
379
+ async replaceAllMatches(newText: string): Promise<boolean> {
380
+ const result = await super.replaceAllMatches(newText);
381
+ // if the cell is rendered force update
382
+ if ((this.cell as MarkdownCell).rendered) {
383
+ this.cell.update();
384
+ }
385
+
386
+ return result;
387
+ }
388
+
389
+ /**
390
+ * Callback on rendered state change
391
+ *
392
+ * @param cell Cell that emitted the change
393
+ * @param rendered New rendered value
394
+ */
395
+ protected onRenderedChanged(cell: MarkdownCell, rendered: boolean): void {
396
+ if (!this._unrenderedByHighligh) {
397
+ this.currentIndex = null;
398
+ }
399
+ this._unrenderedByHighligh = false;
400
+ if (this.isActive) {
401
+ if (rendered) {
402
+ void this.renderedProvider.startQuery(this.query);
403
+ } else {
404
+ // Force cursor position to ensure reverse search is working as expected
405
+ cell.editor?.setCursorPosition({ column: 0, line: 0 });
406
+ void this.renderedProvider.endQuery();
407
+ }
408
+ }
409
+ }
410
+
411
+ protected renderedProvider: GenericSearchProvider;
412
+ private _unrenderedByHighligh = false;
413
+ }
414
+
415
+ /**
416
+ * Factory to create a cell search provider
417
+ *
418
+ * @param cell Cell widget
419
+ * @returns Cell search provider
420
+ */
421
+ export function createCellSearchProvider(
422
+ cell: Cell<ICellModel>
423
+ ): CellSearchProvider {
424
+ if (cell.isPlaceholder()) {
425
+ return new CellSearchProvider(cell);
426
+ }
427
+
428
+ switch (cell.model.type) {
429
+ case 'code':
430
+ return new CodeCellSearchProvider(cell);
431
+ case 'markdown':
432
+ return new MarkdownCellSearchProvider(cell);
433
+ default:
434
+ return new CellSearchProvider(cell);
435
+ }
436
+ }
@@ -0,0 +1,57 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { CodeEditorWrapper, IEditorServices } from '@jupyterlab/codeeditor';
5
+ import {
6
+ CodeMirrorEditorFactory,
7
+ CodeMirrorMimeTypeService,
8
+ EditorLanguageRegistry
9
+ } from '@jupyterlab/codemirror';
10
+ import { CodeCellModel } from './model';
11
+ import { Cell } from './widget';
12
+
13
+ /**
14
+ * The default notebook content.
15
+ */
16
+
17
+ export namespace NBTestUtils {
18
+ const editorServices: IEditorServices = (function () {
19
+ const languages = new EditorLanguageRegistry();
20
+ const factoryService = new CodeMirrorEditorFactory({ languages });
21
+ const mimeTypeService = new CodeMirrorMimeTypeService(languages);
22
+ return {
23
+ factoryService,
24
+ mimeTypeService
25
+ };
26
+ })();
27
+
28
+ export const editorFactory =
29
+ editorServices.factoryService.newInlineEditor.bind(
30
+ editorServices.factoryService
31
+ );
32
+
33
+ export const mimeTypeService = editorServices.mimeTypeService;
34
+ /**
35
+ * Create a base cell content factory.
36
+ */
37
+ export function createBaseCellFactory(): Cell.IContentFactory {
38
+ return new Cell.ContentFactory({ editorFactory });
39
+ }
40
+
41
+ /**
42
+ * Create a new code cell content factory.
43
+ */
44
+ export function createCodeCellFactory(): Cell.IContentFactory {
45
+ return new Cell.ContentFactory({ editorFactory });
46
+ }
47
+
48
+ /**
49
+ * Create a cell editor widget.
50
+ */
51
+ export function createCellEditor(model?: CodeCellModel): CodeEditorWrapper {
52
+ return new CodeEditorWrapper({
53
+ model: model ?? new CodeCellModel(),
54
+ factory: editorFactory
55
+ });
56
+ }
57
+ }