-
Notifications
You must be signed in to change notification settings - Fork 911
/
code.component.ts
366 lines (321 loc) · 15 KB
/
code.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./code';
import { OnInit, Component, Input, Inject, ElementRef, ViewChild, Output, EventEmitter, OnChanges, SimpleChange, forwardRef, ChangeDetectorRef } from '@angular/core';
import { AngularDisposable } from 'sql/base/browser/lifecycle';
import { QueryTextEditor } from 'sql/workbench/browser/modelComponents/queryTextEditor';
import { CellToggleMoreActions } from 'sql/workbench/contrib/notebook/browser/cellToggleMoreActions';
import { ICellModel, notebookConstants, CellExecutionState } from 'sql/workbench/contrib/notebook/browser/models/modelInterfaces';
import { Taskbar } from 'sql/base/browser/ui/taskbar/taskbar';
import { RunCellAction, CellContext } from 'sql/workbench/contrib/notebook/browser/cellViews/codeActions';
import { NotebookModel } from 'sql/workbench/contrib/notebook/browser/models/notebookModel';
import { IColorTheme, IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import * as themeColors from 'vs/workbench/common/theme';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SimpleEditorProgressService } from 'vs/editor/standalone/browser/simpleServices';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ITextModel } from 'vs/editor/common/model';
import * as DOM from 'vs/base/browser/dom';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Event, Emitter } from 'vs/base/common/event';
import { CellTypes } from 'sql/workbench/contrib/notebook/common/models/contracts';
import { OVERRIDE_EDITOR_THEMING_SETTING } from 'sql/workbench/services/notebook/browser/notebookService';
import * as notebookUtils from 'sql/workbench/contrib/notebook/browser/models/notebookUtils';
import { IConnectionManagementService } from 'sql/platform/connection/common/connectionManagement';
import { ILogService } from 'vs/platform/log/common/log';
import { CollapseComponent } from 'sql/workbench/contrib/notebook/browser/cellViews/collapse.component';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { UntitledTextEditorInput } from 'vs/workbench/common/editor/untitledTextEditorInput';
import { UntitledTextEditorModel } from 'vs/workbench/common/editor/untitledTextEditorModel';
export const CODE_SELECTOR: string = 'code-component';
const MARKDOWN_CLASS = 'markdown';
@Component({
selector: CODE_SELECTOR,
templateUrl: decodeURI(require.toUrl('./code.component.html'))
})
export class CodeComponent extends AngularDisposable implements OnInit, OnChanges {
@ViewChild('toolbar', { read: ElementRef }) private toolbarElement: ElementRef;
@ViewChild('moreactions', { read: ElementRef }) private moreActionsElementRef: ElementRef;
@ViewChild('editor', { read: ElementRef }) private codeElement: ElementRef;
@ViewChild(CollapseComponent) private collapseComponent: CollapseComponent;
public get cellModel(): ICellModel {
return this._cellModel;
}
@Input() public set cellModel(value: ICellModel) {
this._cellModel = value;
if (this.toolbarElement && value && value.cellType === CellTypes.Markdown) {
let nativeToolbar = <HTMLElement>this.toolbarElement.nativeElement;
DOM.addClass(nativeToolbar, MARKDOWN_CLASS);
}
}
@Output() public onContentChanged = new EventEmitter<void>();
@Input() set model(value: NotebookModel) {
this._model = value;
this._register(value.kernelChanged(() => {
// On kernel change, need to reevaluate the language for each cell
// Refresh based on the cell magic (since this is kernel-dependent) and then update using notebook language
this.checkForLanguageMagics();
this.updateLanguageMode();
}));
this._register(value.onValidConnectionSelected(() => {
this.updateConnectionState(this.isActive());
}));
}
@Input() set activeCellId(value: string) {
this._activeCellId = value;
}
@Input() set hover(value: boolean) {
this.cellModel.hover = value;
if (!this.isActive()) {
// Only make a change if we're not active, since this has priority
this.toggleActionsVisibility(this.cellModel.hover);
}
}
protected _actionBar: Taskbar;
private readonly _minimumHeight = 30;
private readonly _maximumHeight = 4000;
private _cellModel: ICellModel;
private _editor: QueryTextEditor;
private _editorInput: UntitledTextEditorInput;
private _editorModel: ITextModel;
private _model: NotebookModel;
private _activeCellId: string;
private _cellToggleMoreActions: CellToggleMoreActions;
private _layoutEmitter = new Emitter<void>();
constructor(
@Inject(IWorkbenchThemeService) private themeService: IWorkbenchThemeService,
@Inject(IInstantiationService) private _instantiationService: IInstantiationService,
@Inject(IModelService) private _modelService: IModelService,
@Inject(IModeService) private _modeService: IModeService,
@Inject(IConfigurationService) private _configurationService: IConfigurationService,
@Inject(forwardRef(() => ChangeDetectorRef)) private _changeRef: ChangeDetectorRef,
@Inject(ILogService) private readonly logService: ILogService
) {
super();
this._cellToggleMoreActions = this._instantiationService.createInstance(CellToggleMoreActions);
this._register(Event.debounce(this._layoutEmitter.event, (l, e) => e, 250, /*leading=*/false)
(() => this.layout()));
// Handle disconnect on removal of the cell, if it was the active cell
this._register({ dispose: () => this.updateConnectionState(false) });
}
ngOnInit() {
this._register(this.themeService.onDidColorThemeChange(this.updateTheme, this));
this.updateTheme(this.themeService.getColorTheme());
this.initActionBar();
}
ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
this.updateLanguageMode();
this.updateModel();
for (let propName in changes) {
if (propName === 'activeCellId') {
let changedProp = changes[propName];
let isActive = this.cellModel.id === changedProp.currentValue;
this.updateConnectionState(isActive);
this.toggleActionsVisibility(isActive);
if (this._editor) {
this._editor.toggleEditorSelected(isActive);
}
break;
}
}
}
private updateConnectionState(shouldConnect: boolean) {
if (this.isSqlCodeCell()) {
let cellUri = this.cellModel.cellUri.toString();
let connectionService = this.connectionService;
if (!shouldConnect && connectionService && connectionService.isConnected(cellUri)) {
connectionService.disconnect(cellUri).catch(e => this.logService.error(e));
} else if (shouldConnect && this._model.context && this._model.context.id !== '-1') {
connectionService.connect(this._model.context, cellUri).catch(e => this.logService.error(e));
}
}
}
private get connectionService(): IConnectionManagementService {
return this._model && this._model.notebookOptions && this._model.notebookOptions.connectionService;
}
private isSqlCodeCell() {
return this._model
&& this._model.defaultKernel
&& this._model.defaultKernel.display_name === notebookConstants.SQL
&& this.cellModel.cellType === CellTypes.Code
&& this.cellModel.cellUri;
}
private get destroyed(): boolean {
return !!(this._changeRef['destroyed']);
}
ngAfterContentInit(): void {
if (this.destroyed) {
return;
}
this.createEditor();
this._register(DOM.addDisposableListener(window, DOM.EventType.RESIZE, e => {
this._layoutEmitter.fire();
}));
}
get model(): NotebookModel {
return this._model;
}
get activeCellId(): string {
return this._activeCellId;
}
private async createEditor(): Promise<void> {
let instantiationService = this._instantiationService.createChild(new ServiceCollection([IProgressService, new SimpleEditorProgressService()]));
this._editor = instantiationService.createInstance(QueryTextEditor);
this._editor.create(this.codeElement.nativeElement);
this._editor.setVisible(true);
this._editor.setMinimumHeight(this._minimumHeight);
this._editor.setMaximumHeight(this._maximumHeight);
let uri = this.cellModel.cellUri;
let cellModelSource: string;
cellModelSource = Array.isArray(this.cellModel.source) ? this.cellModel.source.join('') : this.cellModel.source;
this._editorInput = instantiationService.createInstance(UntitledTextEditorInput, uri, false, this.cellModel.language, cellModelSource, '');
await this._editor.setInput(this._editorInput, undefined);
this.setFocusAndScroll();
let untitledEditorModel: UntitledTextEditorModel = await this._editorInput.resolve();
this._editorModel = untitledEditorModel.textEditorModel;
let isActive = this.cellModel.id === this._activeCellId;
this._editor.toggleEditorSelected(isActive);
// For markdown cells, don't show line numbers unless we're using editor defaults
let overrideEditorSetting = this._configurationService.getValue<boolean>(OVERRIDE_EDITOR_THEMING_SETTING);
this._editor.hideLineNumbers = (overrideEditorSetting && this.cellModel.cellType === CellTypes.Markdown);
if (this.destroyed) {
// At this point, we may have been disposed (scenario: restoring markdown cell in preview mode).
// Exiting early to avoid warnings on registering already disposed items, which causes some churning
// due to re-disposing things.
// There's no negative impact as at this point the component isn't visible (it was removed from the DOM)
return;
}
this._register(this._editor);
this._register(this._editorInput);
this._register(this._editorModel.onDidChangeContent(e => {
this.cellModel.modelContentChangedEvent = e;
let originalSourceLength = this.cellModel.source.length;
this.cellModel.source = this._editorModel.getValue();
if (this._cellModel.isCollapsed && originalSourceLength !== this.cellModel.source.length) {
this._cellModel.isCollapsed = false;
}
this._editor.setHeightToScrollHeight(false, this._cellModel.isCollapsed);
this.onContentChanged.emit();
this.checkForLanguageMagics();
}));
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor.wordWrap') || e.affectsConfiguration('editor.fontSize')) {
this._editor.setHeightToScrollHeight(true, this._cellModel.isCollapsed);
}
}));
this._register(this.model.layoutChanged(() => this._layoutEmitter.fire(), this));
this._register(this.cellModel.onExecutionStateChange(event => {
if (event === CellExecutionState.Running && !this.cellModel.stdInVisible) {
this.setFocusAndScroll();
}
}));
this._register(this.cellModel.onCollapseStateChanged(isCollapsed => {
this.onCellCollapse(isCollapsed);
}));
this.layout();
if (this._cellModel.isCollapsed) {
this.onCellCollapse(true);
}
}
public layout(): void {
this._editor.layout(new DOM.Dimension(
DOM.getContentWidth(this.codeElement.nativeElement),
DOM.getContentHeight(this.codeElement.nativeElement)));
this._editor.setHeightToScrollHeight(false, this._cellModel.isCollapsed);
}
protected initActionBar() {
let context = new CellContext(this.model, this.cellModel);
let runCellAction = this._instantiationService.createInstance(RunCellAction, context);
let taskbar = <HTMLElement>this.toolbarElement.nativeElement;
this._actionBar = new Taskbar(taskbar);
this._actionBar.context = context;
this._actionBar.setContent([
{ action: runCellAction }
]);
this._cellToggleMoreActions.onInit(this.moreActionsElementRef, this.model, this.cellModel);
}
/// Editor Functions
private updateModel() {
if (this._editorModel) {
let cellModelSource: string;
cellModelSource = Array.isArray(this.cellModel.source) ? this.cellModel.source.join('') : this.cellModel.source;
this._modelService.updateModel(this._editorModel, cellModelSource);
}
}
private checkForLanguageMagics(): void {
try {
if (!this.cellModel || this.cellModel.cellType !== CellTypes.Code) {
return;
}
if (this._editorModel && this._editor && this._editorModel.getLineCount() > 1) {
// Only try to match once we've typed past the first line
let magicName = notebookUtils.tryMatchCellMagic(this._editorModel.getLineContent(1));
if (magicName) {
let kernelName = this._model.clientSession && this._model.clientSession.kernel ? this._model.clientSession.kernel.name : undefined;
let magic = this._model.notebookOptions.cellMagicMapper.toLanguageMagic(magicName, kernelName);
if (magic && this.cellModel.language !== magic.language) {
this.cellModel.setOverrideLanguage(magic.language);
this.updateLanguageMode();
}
} else {
this.cellModel.setOverrideLanguage(undefined);
}
}
} catch (err) {
// No-op for now. Should we log?
}
}
private updateLanguageMode(): void {
if (this._editorModel && this._editor) {
let modeValue = this._modeService.create(this.cellModel.language);
this._modelService.setMode(this._editorModel, modeValue);
}
}
private updateTheme(theme: IColorTheme): void {
let toolbarEl = <HTMLElement>this.toolbarElement.nativeElement;
toolbarEl.style.borderRightColor = theme.getColor(themeColors.SIDE_BAR_BACKGROUND, true).toString();
let moreActionsEl = <HTMLElement>this.moreActionsElementRef.nativeElement;
moreActionsEl.style.borderRightColor = theme.getColor(themeColors.SIDE_BAR_BACKGROUND, true).toString();
}
private setFocusAndScroll(): void {
// If offsetParent is null, the element isn't visible
// In this case, we don't want a cell to grab focus for an editor that isn't in the foreground.
// In addition, ensure that the ownerDocument itself has focus for scenarios where ADS isn't in the foreground
let ownerDocument = this._editor.getContainer().ownerDocument;
if (this.cellModel.id === this._activeCellId && this._editor.getContainer().offsetParent && ownerDocument && ownerDocument.hasFocus()) {
this._editor.focus();
this._editor.getContainer().scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
}
protected isActive() {
return this.cellModel && this.cellModel.id === this.activeCellId;
}
protected toggleActionsVisibility(isActiveOrHovered: boolean) {
this._cellToggleMoreActions.toggleVisible(!isActiveOrHovered);
if (this.collapseComponent) {
this.collapseComponent.toggleIconVisibility(isActiveOrHovered);
}
}
private onCellCollapse(isCollapsed: boolean): void {
let editorWidget = this._editor.getControl() as ICodeEditor;
if (isCollapsed) {
let model = editorWidget.getModel();
let totalLines = model.getLineCount();
let endColumn = model.getLineMaxColumn(totalLines);
editorWidget.setHiddenAreas([{
startLineNumber: 2,
startColumn: 1,
endLineNumber: totalLines,
endColumn: endColumn
}]);
} else {
editorWidget.setHiddenAreas([]);
}
this._editor.setHeightToScrollHeight(false, isCollapsed);
}
}