Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notebook Cell Tag Support #14271

Merged
merged 2 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/notebook/src/browser/notebook-frontend-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { NotebookOptionsService } from './service/notebook-options';
import { NotebookUndoRedoHandler } from './contributions/notebook-undo-redo-handler';
import { NotebookStatusBarContribution } from './contributions/notebook-status-bar-contribution';
import { NotebookCellEditorService } from './service/notebook-cell-editor-service';
import { NotebookCellStatusBarService } from './service/notebook-cell-status-bar-service';

export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(NotebookColorContribution).toSelf().inSingletonScope();
Expand All @@ -74,6 +75,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(NotebookKernelQuickPickService).toSelf().inSingletonScope();
bind(NotebookClipboardService).toSelf().inSingletonScope();
bind(NotebookCellEditorService).toSelf().inSingletonScope();
bind(NotebookCellStatusBarService).toSelf().inSingletonScope();

bind(NotebookCellResourceResolver).toSelf().inSingletonScope();
bind(ResourceResolver).toService(NotebookCellResourceResolver);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// *****************************************************************************
// Copyright (C) 2024 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { CancellationToken, Command, Disposable, Emitter, Event, URI } from '@theia/core';
import { CellStatusbarAlignment } from '../../common';
import { ThemeColor } from '@theia/core/lib/common/theme';
import { AccessibilityInformation } from '@theia/core/lib/common/accessibility';
import { injectable } from '@theia/core/shared/inversify';
import { MarkdownString } from '@theia/core/lib/common/markdown-rendering';

export interface NotebookCellStatusBarItem {
readonly alignment: CellStatusbarAlignment;
readonly priority?: number;
readonly text: string;
readonly color?: string | ThemeColor;
readonly backgroundColor?: string | ThemeColor;
readonly tooltip?: string | MarkdownString;
readonly command?: string | (Command & { arguments?: unknown[] });
readonly accessibilityInformation?: AccessibilityInformation;
readonly opacity?: string;
readonly onlyShowWhenActive?: boolean;
}
export interface NotebookCellStatusBarItemList {
items: NotebookCellStatusBarItem[];
dispose?(): void;
}

export interface NotebookCellStatusBarItemProvider {
viewType: string;
onDidChangeStatusBarItems?: Event<void>;
provideCellStatusBarItems(uri: URI, index: number, token: CancellationToken): Promise<NotebookCellStatusBarItemList | undefined>;
}

@injectable()
export class NotebookCellStatusBarService implements Disposable {

protected readonly onDidChangeProvidersEmitter = new Emitter<void>();
readonly onDidChangeProviders: Event<void> = this.onDidChangeProvidersEmitter.event;

protected readonly onDidChangeItemsEmitter = new Emitter<void>();
readonly onDidChangeItems: Event<void> = this.onDidChangeItemsEmitter.event;

protected readonly providers: NotebookCellStatusBarItemProvider[] = [];

registerCellStatusBarItemProvider(provider: NotebookCellStatusBarItemProvider): Disposable {
this.providers.push(provider);
let changeListener: Disposable | undefined;
if (provider.onDidChangeStatusBarItems) {
changeListener = provider.onDidChangeStatusBarItems(() => this.onDidChangeItemsEmitter.fire());
}

this.onDidChangeProvidersEmitter.fire();

return Disposable.create(() => {
changeListener?.dispose();
const idx = this.providers.findIndex(p => p === provider);
this.providers.splice(idx, 1);
});
}

async getStatusBarItemsForCell(notebookUri: URI, cellIndex: number, viewType: string, token: CancellationToken): Promise<NotebookCellStatusBarItemList[]> {
const providers = this.providers.filter(p => p.viewType === viewType || p.viewType === '*');
return Promise.all(providers.map(async p => {
try {
return await p.provideCellStatusBarItems(notebookUri, cellIndex, token) ?? { items: [] };
} catch (e) {
console.error(e);
return { items: [] };
}
}));
}

dispose(): void {
this.onDidChangeItemsEmitter.dispose();
this.onDidChangeProvidersEmitter.dispose();
}
}
19 changes: 19 additions & 0 deletions packages/notebook/src/browser/style/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,22 @@ mark.theia-find-match.theia-find-match-selected {
color: var(--theia-editor-findMatchForeground);
background-color: var(--theia-editor-findMatchBackground);
}

.cell-status-bar-item {
align-items: center;
display: flex;
height: 16px;
margin: 0 3px;
overflow: hidden;
padding: 0 3px;
text-overflow: clip;
white-space: pre;
}

.cell-status-item-has-command {
cursor: pointer;
}

.cell-status-item-has-command:hover {
background-color: var(--theia-toolbar-hoverBackground);
}
69 changes: 65 additions & 4 deletions packages/notebook/src/browser/view/notebook-code-cell-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { NotebookCellActionContribution, NotebookCellCommands } from '../contrib
import { CellExecution, NotebookExecutionStateService } from '../service/notebook-execution-state-service';
import { codicon } from '@theia/core/lib/browser';
import { NotebookCellExecutionState } from '../../common';
import { CommandRegistry, DisposableCollection, nls } from '@theia/core';
import { CancellationToken, CommandRegistry, DisposableCollection, nls } from '@theia/core';
import { NotebookContextManager } from '../service/notebook-context-manager';
import { NotebookViewportService } from './notebook-viewport-service';
import { EditorPreferences } from '@theia/editor/lib/browser';
Expand All @@ -36,6 +36,8 @@ import { MarkdownRenderer } from '@theia/core/lib/browser/markdown-rendering/mar
import { MarkdownString } from '@theia/monaco-editor-core/esm/vs/base/common/htmlContent';
import { NotebookCellEditorService } from '../service/notebook-cell-editor-service';
import { CellOutputWebview } from '../renderers/cell-output-webview';
import { NotebookCellStatusBarItem, NotebookCellStatusBarItemList, NotebookCellStatusBarService } from '../service/notebook-cell-status-bar-service';
import { LabelParser } from '@theia/core/lib/browser/label-parser';

@injectable()
export class NotebookCodeCellRenderer implements CellRenderer {
Expand Down Expand Up @@ -75,6 +77,12 @@ export class NotebookCodeCellRenderer implements CellRenderer {
@inject(CellOutputWebview)
protected readonly outputWebview: CellOutputWebview;

@inject(NotebookCellStatusBarService)
protected readonly notebookCellStatusBarService: NotebookCellStatusBarService;

@inject(LabelParser)
protected readonly labelParser: LabelParser;

render(notebookModel: NotebookModel, cell: NotebookCellModel, handle: number): React.ReactNode {
return <div className='theia-notebook-cell-with-sidebar' ref={ref => observeCellHeight(ref, cell)}>
<div className='theia-notebook-cell-editor-container'>
Expand All @@ -87,6 +95,8 @@ export class NotebookCodeCellRenderer implements CellRenderer {
<NotebookCodeCellStatus cell={cell} notebook={notebookModel}
commandRegistry={this.commandRegistry}
executionStateService={this.executionStateService}
cellStatusBarService={this.notebookCellStatusBarService}
labelParser={this.labelParser}
onClick={() => cell.requestFocusEditor()} />
</div >
</div >;
Expand Down Expand Up @@ -182,7 +192,9 @@ export interface NotebookCodeCellStatusProps {
notebook: NotebookModel;
cell: NotebookCellModel;
commandRegistry: CommandRegistry;
cellStatusBarService: NotebookCellStatusBarService;
executionStateService?: NotebookExecutionStateService;
labelParser: LabelParser;
onClick: () => void;
}

Expand All @@ -195,6 +207,8 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat

protected toDispose = new DisposableCollection();

protected statusBarItems: NotebookCellStatusBarItemList[] = [];

constructor(props: NotebookCodeCellStatusProps) {
super(props);

Expand Down Expand Up @@ -225,6 +239,19 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat
this.toDispose.push(props.cell.onDidChangeLanguage(() => {
this.forceUpdate();
}));

this.updateStatusBarItems();
this.props.cellStatusBarService.onDidChangeItems(() => this.updateStatusBarItems());
this.props.notebook.onContentChanged(() => this.updateStatusBarItems());
}

async updateStatusBarItems(): Promise<void> {
this.statusBarItems = await this.props.cellStatusBarService.getStatusBarItemsForCell(
this.props.notebook.uri,
this.props.notebook.cells.indexOf(this.props.cell),
this.props.notebook.viewType,
CancellationToken.None);
this.forceUpdate();
}

override componentWillUnmount(): void {
Expand All @@ -235,6 +262,7 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat
return <div className='notebook-cell-status' onClick={() => this.props.onClick()}>
<div className='notebook-cell-status-left'>
{this.props.executionStateService && this.renderExecutionState()}
{this.statusBarItems?.length && this.renderStatusBarItems()}
</div>
<div className='notebook-cell-status-right'>
<span className='notebook-cell-language-label' onClick={() => {
Expand All @@ -244,7 +272,7 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat
</div>;
}

private renderExecutionState(): React.ReactNode {
protected renderExecutionState(): React.ReactNode {
const state = this.state.currentExecution?.state;
const { lastRunSuccess } = this.props.cell.internalMetadata;

Expand All @@ -270,7 +298,7 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat
</>;
}

private getExecutionTime(): number {
protected getExecutionTime(): number {
const { runStartTime, runEndTime } = this.props.cell.internalMetadata;
const { executionTime } = this.state;
if (runStartTime !== undefined && runEndTime !== undefined) {
Expand All @@ -279,9 +307,42 @@ export class NotebookCodeCellStatus extends React.Component<NotebookCodeCellStat
return executionTime;
}

private renderTime(ms: number): string {
protected renderTime(ms: number): string {
return `${(ms / 1000).toLocaleString(undefined, { maximumFractionDigits: 1, minimumFractionDigits: 1 })}s`;
}

protected renderStatusBarItems(): React.ReactNode {
return <>
{
this.statusBarItems.flatMap((itemList, listIndex) =>
itemList.items.map((item, index) => this.renderStatusBarItem(item, `${listIndex}-${index}`)
)
)
}
</>;
}

protected renderStatusBarItem(item: NotebookCellStatusBarItem, key: string): React.ReactNode {
const content = this.props.labelParser.parse(item.text).map(part => {
if (typeof part === 'string') {
return part;
} else {
return <span key={part.name} className={`codicon codicon-${part.name}`}></span>;
}
});
return <div key={key} className={`cell-status-bar-item ${item.command ? 'cell-status-item-has-command' : ''}`} onClick={async () => {
if (item.command) {
if (typeof item.command === 'string') {
this.props.commandRegistry.executeCommand(item.command);
} else {
this.props.commandRegistry.executeCommand(item.command.id, ...(item.command.arguments ?? []));
}
}
}}>
{content}
</div>;
}

}

interface NotebookCellOutputProps {
Expand Down
23 changes: 20 additions & 3 deletions packages/notebook/src/browser/view/notebook-markdown-cell-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { NotebookCodeCellStatus } from './notebook-code-cell-view';
import { NotebookEditorFindMatch, NotebookEditorFindMatchOptions } from './notebook-find-widget';
import * as mark from 'advanced-mark.js';
import { NotebookCellEditorService } from '../service/notebook-cell-editor-service';
import { NotebookCellStatusBarService } from '../service/notebook-cell-status-bar-service';
import { LabelParser } from '@theia/core/lib/browser/label-parser';

@injectable()
export class NotebookMarkdownCellRenderer implements CellRenderer {
Expand All @@ -51,6 +53,12 @@ export class NotebookMarkdownCellRenderer implements CellRenderer {
@inject(NotebookCellEditorService)
protected readonly notebookCellEditorService: NotebookCellEditorService;

@inject(NotebookCellStatusBarService)
protected readonly notebookCellStatusBarService: NotebookCellStatusBarService;

@inject(LabelParser)
protected readonly labelParser: LabelParser;

render(notebookModel: NotebookModel, cell: NotebookCellModel): React.ReactNode {
return <MarkdownCell
markdownRenderer={this.markdownRenderer}
Expand All @@ -60,7 +68,10 @@ export class NotebookMarkdownCellRenderer implements CellRenderer {
cell={cell}
notebookModel={notebookModel}
notebookContextManager={this.notebookContextManager}
notebookCellEditorService={this.notebookCellEditorService} />;
notebookCellEditorService={this.notebookCellEditorService}
notebookCellStatusBarService={this.notebookCellStatusBarService}
labelParser={this.labelParser}
/>;
}

renderSidebar(notebookModel: NotebookModel, cell: NotebookCellModel): React.ReactNode {
Expand All @@ -86,11 +97,15 @@ interface MarkdownCellProps {
notebookModel: NotebookModel;
notebookContextManager: NotebookContextManager;
notebookOptionsService: NotebookOptionsService;
notebookCellEditorService: NotebookCellEditorService
notebookCellEditorService: NotebookCellEditorService;
notebookCellStatusBarService: NotebookCellStatusBarService;
labelParser: LabelParser;
}

function MarkdownCell({
markdownRenderer, monacoServices, cell, notebookModel, notebookContextManager, notebookOptionsService, commandRegistry, notebookCellEditorService
markdownRenderer, monacoServices, cell, notebookModel, notebookContextManager,
notebookOptionsService, commandRegistry, notebookCellEditorService, notebookCellStatusBarService,
labelParser
}: MarkdownCellProps): React.JSX.Element {
const [editMode, setEditMode] = React.useState(cell.editing);
let empty = false;
Expand Down Expand Up @@ -147,6 +162,8 @@ function MarkdownCell({
fontInfo={notebookOptionsService.editorFontInfo} />
<NotebookCodeCellStatus cell={cell} notebook={notebookModel}
commandRegistry={commandRegistry}
cellStatusBarService={notebookCellStatusBarService}
labelParser={labelParser}
onClick={() => cell.requestFocusEditor()} />
</div >) :
(<div className='theia-notebook-markdown-content' key="markdown"
Expand Down
Loading
Loading