Skip to content

Commit

Permalink
Create code snippet from whole cells (#1199) (#2726)
Browse files Browse the repository at this point in the history
Co-authored-by: Alan Chin <akchin@us.ibm.com>
  • Loading branch information
xlegs and akchinSTC authored Jun 1, 2022
1 parent 6597761 commit 6bc4fb3
Show file tree
Hide file tree
Showing 3 changed files with 189 additions and 5 deletions.
12 changes: 10 additions & 2 deletions docs/source/user_guide/code-snippets.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,16 @@ To access the panel in JupyterLab:

To create a code snippet:
1. Open the `Code Snippets` panel.
1. Click `+`. You can also highlight the desired text in the editor, right click, and choose `Save As Code Snippet` from the context menu.
![Add code snippet from text](../images/user_guide/code-snippets/add-code-snippet-from-text.png)
1. You can create a new code snippet in 3 ways:

- Click `+`.
- Highlight the desired text in the editor, right click, and choose `Save As Code Snippet` from the context menu.
![Add code snippet from text](../images/user_guide/code-snippets/add-code-snippet-from-text.png)
- Select one or more cells, right click, and choose `Save As Code Snippet` from the context menu.

- Use `Shift + Click` to select multiple cells.
- When multiple cells are selected, their contents will be combined into a single snippet. Each cell's contents will be separated by an empty line.
- If you want to make a snippet from one or more cells, there must not be any highlighted text. If text is highlighted, only the highlighted text will be added to the snippet. Any other selected cells will be ignored.

1. Enter a code snippet display name, an optional description, and tag the code snippet to make it more easily discoverable.
1. Define the code snippet. Refer to the [Code snippet properties](#code-snippet-properties) for details.
Expand Down
45 changes: 42 additions & 3 deletions packages/code-snippet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import {
ILayoutRestorer
} from '@jupyterlab/application';
import { ICommandPalette, IThemeManager } from '@jupyterlab/apputils';
import { Cell } from '@jupyterlab/cells';
import { IEditorServices } from '@jupyterlab/codeeditor';
import { DocumentWidget } from '@jupyterlab/docregistry';
import { FileEditor } from '@jupyterlab/fileeditor';
import { MarkdownDocument } from '@jupyterlab/markdownviewer';
import { Notebook, NotebookPanel } from '@jupyterlab/notebook';

import { Widget } from '@lumino/widgets';

import {
Expand Down Expand Up @@ -100,9 +100,16 @@ export const code_snippet_extension: JupyterFrontEndPlugin<void> = {
selection = document.getSelection()?.toString() ?? '';
}

if (selection) {
if (selection.length > 0) {
return true;
}

if (isNotebookEditor(currentWidget)) {
if (getSelectedCellContents().length > 0) {
return true;
}
}

return false;
},
isVisible: () => true,
Expand All @@ -117,14 +124,24 @@ export const code_snippet_extension: JupyterFrontEndPlugin<void> = {
selection = document.getSelection()?.toString() ?? '';
}

if (selection) {
if (selection.length > 0) {
codeSnippetWidget.openMetadataEditor({
schemaspace: CODE_SNIPPET_SCHEMASPACE,
schema: CODE_SNIPPET_SCHEMA,
code: selection.split('\n'),
onSave: codeSnippetWidget.updateMetadata
});
}

const selectedCells = getSelectedCellContents();
const code = selectedCells.join('\n\n').split('\n');

codeSnippetWidget.openMetadataEditor({
schemaspace: CODE_SNIPPET_SCHEMASPACE,
schema: CODE_SNIPPET_SCHEMA,
code: code,
onSave: codeSnippetWidget.updateMetadata
});
}
});

Expand Down Expand Up @@ -160,6 +177,28 @@ export const code_snippet_extension: JupyterFrontEndPlugin<void> = {
return selection;
};

const getSelectedCellContents = (): string[] => {
const currentWidget = app.shell.currentWidget;
const notebookWidget = currentWidget as NotebookPanel;
const notebook = notebookWidget.content as Notebook;
const notebookCell = notebook.activeCell;
const selectedCells: string[] = [];

if (notebookCell) {
const allCells = notebook.widgets;

allCells.forEach((cell: Cell) => {
if (notebook.isSelectedOrActive(cell)) {
const contents: string = cell.model.toJSON().source.toString();

if (contents.length > 0) selectedCells.push(contents);
}
});
}

return selectedCells;
};

const isFileEditor = (currentWidget: any): boolean => {
return (
currentWidget instanceof DocumentWidget &&
Expand Down
137 changes: 137 additions & 0 deletions tests/integration/codesnippetfromselectedcells.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* Copyright 2018-2022 Elyra Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const cellSelector =
'div.CodeMirror-lines[role="presentation"] > div[role="presentation"]';

describe('Code snippet from cells tests', () => {
beforeEach(() => {
cy.resetJupyterLab();

// Create new python notebook
cy.get(
'.jp-LauncherCard[data-category="Notebook"][title="Python 3 (ipykernel)"]'
).click();

cy.wait(2000);
});

it('test empty cell', () => {
cy.get(cellSelector)
.first()
.rightclick();

cy.wait(2000);

cy.get(
'li.lm-Menu-item[data-command="codesnippet:save-as-snippet"]'
).should('have.class', 'p-mod-disabled');
});

it('test 1 cell', () => {
// Create new cell
cy.get(
'.jp-NotebookPanel-toolbar > div:nth-child(2) > button:nth-child(1)'
).click();

cy.wait(2000);

populateCells();

cy.get(cellSelector)
.first()
.rightclick({
force: true
});

cy.wait(2000);

cy.get(
'li.lm-Menu-item[data-command="codesnippet:save-as-snippet"]'
).click();

cy.wait(2000);

// Verify snippet editor contents
cy.get('span[role="presentation"]:visible').should(
'have.text',
'print("test")'
);
});

it('test 2 cells', () => {
// Create new cells
cy.get(
'.jp-NotebookPanel-toolbar > div:nth-child(2) > button:nth-child(1)'
).click();

cy.wait(2000);

populateCells();

// Select all cells
cy.get(
':nth-child(1) > .jp-Cell-inputWrapper > .jp-InputArea > .jp-InputPrompt'
)
.first()
.click({
shiftKey: true
});

cy.get('div.lm-Widget.p-Widget.jp-InputPrompt.jp-InputArea-prompt:visible')
.first()
.rightclick({
force: true
});

cy.wait(2000);

cy.get(
'li.lm-Menu-item[data-command="codesnippet:save-as-snippet"]'
).click();

cy.wait(2000);

// Verify snippet editor contents
cy.get(
'.elyra-form-code > .CodeMirror > .CodeMirror-scroll span[role="presentation"]:contains("test")'
).should('have.length', 2);
});
});

// ------------------------------
// ----- Utility Functions
// ------------------------------

// Populate cells
const populateCells = (): void => {
cy.get('span[role="presentation"]').each(cell => {
cy.get(cell).type('print("test")');
dismissAssistant();
});
};

// Dismiss LSP code assistant box if visible
const dismissAssistant = (): void => {
cy.get('body').then($body => {
if ($body.find('.lsp-completer').length > 0) {
// Dismiss code assistant box
cy.get('body')
.first()
.type('{esc}');
}
});
};

0 comments on commit 6bc4fb3

Please sign in to comment.