cellComponents.ts 34.3 KB
Newer Older
R
rebornix 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as DOM from 'vs/base/browser/dom';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
R
rebornix 已提交
8
import { IDiffEditorOptions, IEditorOptions } from 'vs/editor/common/config/editorOptions';
R
rebornix 已提交
9
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
R
rebornix 已提交
10
import { CellDiffViewModel, PropertyFoldingState } from 'vs/workbench/contrib/notebook/browser/diff/celllDiffViewModel';
R
rebornix 已提交
11
import { CellDiffRenderTemplate, CellDiffViewModelLayoutChangeEvent, DIFF_CELL_MARGIN, INotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/common';
R
rebornix 已提交
12 13
import { EDITOR_BOTTOM_PADDING, EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
R
rebornix 已提交
14
import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditorWidget';
15
import { renderCodicons } from 'vs/base/browser/codicons';
R
rebornix 已提交
16 17 18 19
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { format } from 'vs/base/common/jsonFormatter';
import { applyEdits } from 'vs/base/common/jsonEdit';
R
rebornix 已提交
20
import { CellEditType, CellUri, NotebookCellMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon';
21
import { hash } from 'vs/base/common/hash';
22 23 24 25 26 27 28 29 30
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IMenu, IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';
import { CodiconActionViewItem } from 'vs/workbench/contrib/notebook/browser/view/renderers/commonViewComponents';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction } from 'vs/base/common/actions';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
R
rebornix 已提交
31

R
rebornix 已提交
32
const fixedEditorOptions: IEditorOptions = {
R
rebornix 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
	padding: {
		top: 12,
		bottom: 12
	},
	scrollBeyondLastLine: false,
	scrollbar: {
		verticalScrollbarSize: 14,
		horizontal: 'auto',
		useShadows: true,
		verticalHasArrows: false,
		horizontalHasArrows: false,
		alwaysConsumeMouseWheel: false
	},
	renderLineHighlightOnlyWhenFocus: true,
	overviewRulerLanes: 0,
	selectOnLineNumbers: false,
	wordWrap: 'off',
	lineNumbers: 'off',
	lineDecorationsWidth: 0,
R
rebornix 已提交
52
	glyphMargin: false,
R
rebornix 已提交
53 54
	fixedOverflowWidgets: true,
	minimap: { enabled: false },
R
rebornix 已提交
55
	renderValidationDecorations: 'on',
R
rebornix 已提交
56 57 58 59 60 61 62
	renderLineHighlight: 'none',
	readOnly: true
};

const fixedDiffEditorOptions: IDiffEditorOptions = {
	...fixedEditorOptions,
	glyphMargin: true,
R
rebornix 已提交
63
	enableSplitViewResizing: false,
R
rebornix 已提交
64
	renderIndicators: false,
R
rebornix 已提交
65
	readOnly: false
R
rebornix 已提交
66 67
};

R
rebornix 已提交
68

R
rebornix 已提交
69

R
rebornix 已提交
70 71 72
class PropertyHeader extends Disposable {
	protected _foldingIndicator!: HTMLElement;
	protected _statusSpan!: HTMLElement;
73 74
	protected _toolbar!: ToolBar;
	protected _menu!: IMenu;
R
rebornix 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87

	constructor(
		readonly cell: CellDiffViewModel,
		readonly metadataHeaderContainer: HTMLElement,
		readonly notebookEditor: INotebookTextDiffEditor,
		readonly accessor: {
			updateInfoRendering: () => void;
			checkIfModified: (cell: CellDiffViewModel) => boolean;
			getFoldingState: (cell: CellDiffViewModel) => PropertyFoldingState;
			updateFoldingState: (cell: CellDiffViewModel, newState: PropertyFoldingState) => void;
			unChangedLabel: string;
			changedLabel: string;
			prefix: string;
88 89 90 91 92 93 94
			menuId: MenuId;
		},
		@IContextMenuService readonly contextMenuService: IContextMenuService,
		@IKeybindingService readonly keybindingService: IKeybindingService,
		@INotificationService readonly notificationService: INotificationService,
		@IMenuService readonly menuService: IMenuService,
		@IContextKeyService readonly contextKeyService: IContextKeyService
R
rebornix 已提交
95 96 97 98 99 100 101
	) {
		super();
	}

	buildHeader(): void {
		let metadataChanged = this.accessor.checkIfModified(this.cell);
		this._foldingIndicator = DOM.append(this.metadataHeaderContainer, DOM.$('.property-folding-indicator'));
102
		this._foldingIndicator.classList.add(this.accessor.prefix);
R
rebornix 已提交
103 104 105 106 107 108 109
		this._updateFoldingIcon();
		const metadataStatus = DOM.append(this.metadataHeaderContainer, DOM.$('div.property-status'));
		this._statusSpan = DOM.append(metadataStatus, DOM.$('span'));

		if (metadataChanged) {
			this._statusSpan.textContent = this.accessor.changedLabel;
			this._statusSpan.style.fontWeight = 'bold';
110
			this.metadataHeaderContainer.classList.add('modified');
R
rebornix 已提交
111 112 113 114
		} else {
			this._statusSpan.textContent = this.accessor.unChangedLabel;
		}

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
		const cellToolbarContainer = DOM.append(this.metadataHeaderContainer, DOM.$('div.property-toolbar'));
		this._toolbar = new ToolBar(cellToolbarContainer, this.contextMenuService, {
			actionViewItemProvider: action => {
				if (action instanceof MenuItemAction) {
					const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService, this.contextMenuService);
					return item;
				}

				return undefined;
			}
		});
		this._toolbar.context = {
			cell: this.cell
		};

		this._menu = this.menuService.createMenu(this.accessor.menuId, this.contextKeyService);

		if (metadataChanged) {
			const actions: IAction[] = [];
			createAndFillInActionBarActions(this._menu, { shouldForwardArgs: true }, actions);
			this._toolbar.setActions(actions);
		}

R
rebornix 已提交
138 139 140 141 142 143 144
		this._register(this.notebookEditor.onMouseUp(e => {
			if (!e.event.target) {
				return;
			}

			const target = e.event.target as HTMLElement;

145
			if (target.classList.contains('codicon-chevron-down') || target.classList.contains('codicon-chevron-right')) {
R
rebornix 已提交
146 147 148 149 150 151
				const parent = target.parentElement as HTMLElement;

				if (!parent) {
					return;
				}

152
				if (!parent.classList.contains(this.accessor.prefix)) {
R
rebornix 已提交
153 154 155
					return;
				}

156
				if (!parent.classList.contains('property-folding-indicator')) {
R
rebornix 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
					return;
				}

				// folding icon

				const cellViewModel = e.target;

				if (cellViewModel === this.cell) {
					const oldFoldingState = this.accessor.getFoldingState(this.cell);
					this.accessor.updateFoldingState(this.cell, oldFoldingState === PropertyFoldingState.Expanded ? PropertyFoldingState.Collapsed : PropertyFoldingState.Expanded);
					this._updateFoldingIcon();
					this.accessor.updateInfoRendering();
				}
			}

			return;
		}));

		this._updateFoldingIcon();
		this.accessor.updateInfoRendering();
	}

179 180 181 182 183
	refresh() {
		let metadataChanged = this.accessor.checkIfModified(this.cell);
		if (metadataChanged) {
			this._statusSpan.textContent = this.accessor.changedLabel;
			this._statusSpan.style.fontWeight = 'bold';
184
			this.metadataHeaderContainer.classList.add('modified');
185 186 187 188 189 190 191 192 193 194
			const actions: IAction[] = [];
			createAndFillInActionBarActions(this._menu, undefined, actions);
			this._toolbar.setActions(actions);
		} else {
			this._statusSpan.textContent = this.accessor.unChangedLabel;
			this._statusSpan.style.fontWeight = 'normal';
			this._toolbar.setActions([]);
		}
	}

R
rebornix 已提交
195 196
	private _updateFoldingIcon() {
		if (this.accessor.getFoldingState(this.cell) === PropertyFoldingState.Collapsed) {
197
			DOM.reset(this._foldingIndicator, ...renderCodicons('$(chevron-right)'));
R
rebornix 已提交
198
		} else {
199
			DOM.reset(this._foldingIndicator, ...renderCodicons('$(chevron-down)'));
R
rebornix 已提交
200 201 202 203
		}
	}
}

R
rebornix 已提交
204
abstract class AbstractCellRenderer extends Disposable {
R
rebornix 已提交
205
	protected _metadataHeaderContainer!: HTMLElement;
R
rebornix 已提交
206
	protected _metadataHeader!: PropertyHeader;
R
rebornix 已提交
207
	protected _metadataInfoContainer!: HTMLElement;
R
rebornix 已提交
208 209 210 211 212 213 214 215 216 217 218 219
	protected _metadataEditorContainer?: HTMLElement;
	protected _metadataEditorDisposeStore!: DisposableStore;
	protected _metadataEditor?: CodeEditorWidget | DiffEditorWidget;

	protected _outputHeaderContainer!: HTMLElement;
	protected _outputHeader!: PropertyHeader;
	protected _outputInfoContainer!: HTMLElement;
	protected _outputEditorContainer?: HTMLElement;
	protected _outputEditorDisposeStore!: DisposableStore;
	protected _outputEditor?: CodeEditorWidget | DiffEditorWidget;


220 221
	protected _diffEditorContainer!: HTMLElement;
	protected _diagonalFill?: HTMLElement;
R
rebornix 已提交
222 223 224 225 226
	protected _layoutInfo!: {
		editorHeight: number;
		editorMargin: number;
		metadataStatusHeight: number;
		metadataHeight: number;
R
rebornix 已提交
227 228
		outputStatusHeight: number;
		outputHeight: number;
229
		bodyMargin: number;
R
rebornix 已提交
230 231
	};

R
rebornix 已提交
232 233 234
	constructor(
		readonly notebookEditor: INotebookTextDiffEditor,
		readonly cell: CellDiffViewModel,
R
rebornix 已提交
235
		readonly templateData: CellDiffRenderTemplate,
236
		readonly style: 'left' | 'right' | 'full',
R
rebornix 已提交
237
		protected readonly instantiationService: IInstantiationService,
R
rebornix 已提交
238 239 240
		protected readonly modeService: IModeService,
		protected readonly modelService: IModelService,

R
rebornix 已提交
241 242
	) {
		super();
R
rebornix 已提交
243 244 245
		// init
		this._layoutInfo = {
			editorHeight: 0,
246
			editorMargin: 0,
R
rebornix 已提交
247
			metadataHeight: 0,
248
			metadataStatusHeight: 25,
R
rebornix 已提交
249 250
			outputHeight: 0,
			outputStatusHeight: 25,
R
rebornix 已提交
251
			bodyMargin: 32
R
rebornix 已提交
252
		};
R
rebornix 已提交
253
		this._metadataEditorDisposeStore = new DisposableStore();
R
rebornix 已提交
254
		this._outputEditorDisposeStore = new DisposableStore();
R
rebornix 已提交
255
		this._register(this._metadataEditorDisposeStore);
R
rebornix 已提交
256 257
		this.initData();
		this.buildBody(templateData.container);
R
rebornix 已提交
258 259 260
		this._register(cell.onDidLayoutChange(e => this.onDidLayoutChange(e)));
	}

R
rebornix 已提交
261
	buildBody(container: HTMLElement) {
262 263 264 265 266
		const body = DOM.$('.cell-body');
		DOM.append(container, body);
		this._diffEditorContainer = DOM.$('.cell-diff-editor-container');
		switch (this.style) {
			case 'left':
267
				body.classList.add('left');
268 269
				break;
			case 'right':
270
				body.classList.add('right');
271 272
				break;
			default:
273
				body.classList.add('full');
274 275 276 277 278 279 280
				break;
		}

		DOM.append(body, this._diffEditorContainer);
		this._diagonalFill = DOM.append(body, DOM.$('.diagonal-fill'));
		this.styleContainer(this._diffEditorContainer);
		const sourceContainer = DOM.append(this._diffEditorContainer, DOM.$('.source-container'));
R
rebornix 已提交
281 282
		this.buildSourceEditor(sourceContainer);

283 284
		this._metadataHeaderContainer = DOM.append(this._diffEditorContainer, DOM.$('.metadata-header-container'));
		this._metadataInfoContainer = DOM.append(this._diffEditorContainer, DOM.$('.metadata-info-container'));
285

286 287 288 289 290 291 292 293
		const checkIfModified = (cell: CellDiffViewModel) => {
			return cell.type !== 'delete' && cell.type !== 'insert' && hash(this._getFormatedMetadataJSON(cell.original?.metadata || {}, cell.original?.language)) !== hash(this._getFormatedMetadataJSON(cell.modified?.metadata ?? {}, cell.modified?.language));
		};

		if (checkIfModified(this.cell)) {
			this.cell.metadataFoldingState = PropertyFoldingState.Expanded;
		}

294 295
		this._metadataHeader = this.instantiationService.createInstance(
			PropertyHeader,
R
rebornix 已提交
296 297 298 299 300 301
			this.cell,
			this._metadataHeaderContainer,
			this.notebookEditor,
			{
				updateInfoRendering: this.updateMetadataRendering.bind(this),
				checkIfModified: (cell) => {
302
					return checkIfModified(cell);
R
rebornix 已提交
303 304 305 306 307 308 309 310 311
				},
				getFoldingState: (cell) => {
					return cell.metadataFoldingState;
				},
				updateFoldingState: (cell, state) => {
					cell.metadataFoldingState = state;
				},
				unChangedLabel: 'Metadata',
				changedLabel: 'Metadata changed',
312 313
				prefix: 'metadata',
				menuId: MenuId.NotebookDiffCellMetadataTitle
R
rebornix 已提交
314
			}
R
rebornix 已提交
315 316 317 318
		);
		this._register(this._metadataHeader);
		this._metadataHeader.buildHeader();

R
rebornix 已提交
319 320 321 322 323 324 325
		if (this.notebookEditor.textModel?.transientOptions.transientOutputs) {
			this._layoutInfo.outputHeight = 0;
			this._layoutInfo.outputStatusHeight = 0;
			this.layout({});
			return;
		}

R
rebornix 已提交
326 327 328
		this._outputHeaderContainer = DOM.append(this._diffEditorContainer, DOM.$('.output-header-container'));
		this._outputInfoContainer = DOM.append(this._diffEditorContainer, DOM.$('.output-info-container'));

329 330 331 332 333 334 335 336
		const checkIfOutputsModified = (cell: CellDiffViewModel) => {
			return cell.type !== 'delete' && cell.type !== 'insert' && !this.notebookEditor.textModel!.transientOptions.transientOutputs && cell.type === 'modified' && hash(cell.original?.outputs ?? []) !== hash(cell.modified?.outputs ?? []);
		};

		if (checkIfOutputsModified(this.cell)) {
			this.cell.outputFoldingState = PropertyFoldingState.Expanded;
		}

337 338
		this._outputHeader = this.instantiationService.createInstance(
			PropertyHeader,
R
rebornix 已提交
339 340 341 342 343 344
			this.cell,
			this._outputHeaderContainer,
			this.notebookEditor,
			{
				updateInfoRendering: this.updateOutputRendering.bind(this),
				checkIfModified: (cell) => {
345
					return checkIfOutputsModified(cell);
R
rebornix 已提交
346 347
				},
				getFoldingState: (cell) => {
348
					return cell.outputFoldingState;
R
rebornix 已提交
349 350 351 352 353 354
				},
				updateFoldingState: (cell, state) => {
					cell.outputFoldingState = state;
				},
				unChangedLabel: 'Outputs',
				changedLabel: 'Outputs changed',
355 356
				prefix: 'output',
				menuId: MenuId.NotebookDiffCellOutputsTitle
R
rebornix 已提交
357
			}
R
rebornix 已提交
358 359 360
		);
		this._register(this._outputHeader);
		this._outputHeader.buildHeader();
R
rebornix 已提交
361 362 363
	}

	updateMetadataRendering() {
R
rebornix 已提交
364
		if (this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
R
rebornix 已提交
365 366 367 368 369 370
			// we should expand the metadata editor
			this._metadataInfoContainer.style.display = 'block';

			if (!this._metadataEditorContainer || !this._metadataEditor) {
				// create editor
				this._metadataEditorContainer = DOM.append(this._metadataInfoContainer, DOM.$('.metadata-editor-container'));
371 372 373 374 375 376 377 378 379 380 381 382
				this._buildMetadataEditor();
			} else {
				this._layoutInfo.metadataHeight = this._metadataEditor.getContentHeight();
				this.layout({ metadataEditor: true });
			}
		} else {
			// we should collapse the metadata editor
			this._metadataInfoContainer.style.display = 'none';
			this._metadataEditorDisposeStore.clear();
			this._layoutInfo.metadataHeight = 0;
			this.layout({});
		}
R
rebornix 已提交
383
	}
R
rebornix 已提交
384

R
rebornix 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	updateOutputRendering() {
		if (this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
			this._outputInfoContainer.style.display = 'block';

			if (!this._outputEditorContainer || !this._outputEditor) {
				// create editor
				this._outputEditorContainer = DOM.append(this._outputInfoContainer, DOM.$('.output-editor-container'));
				this._buildOutputEditor();
			} else {
				this._layoutInfo.outputHeight = this._outputEditor.getContentHeight();
				this.layout({ outputEditor: true });
			}
		} else {
			this._outputInfoContainer.style.display = 'none';
			this._outputEditorDisposeStore.clear();
			this._layoutInfo.outputHeight = 0;
			this.layout({});
		}
403 404
	}

405
	protected _getFormatedMetadataJSON(metadata: NotebookCellMetadata, language?: string) {
R
rebornix 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
		let filteredMetadata: { [key: string]: any } = {};

		if (this.notebookEditor.textModel) {
			const transientMetadata = this.notebookEditor.textModel!.transientOptions.transientMetadata;

			const keys = new Set([...Object.keys(metadata)]);
			for (let key of keys) {
				if (!(transientMetadata[key as keyof NotebookCellMetadata])
				) {
					filteredMetadata[key] = metadata[key as keyof NotebookCellMetadata];
				}
			}
		} else {
			filteredMetadata = metadata;
		}

R
rebornix 已提交
422 423
		const content = JSON.stringify({
			language,
424
			...filteredMetadata
R
rebornix 已提交
425 426
		});

427 428 429 430 431 432
		const edits = format(content, undefined, {});
		const metadataSource = applyEdits(content, edits);

		return metadataSource;
	}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
	private _applySanitizedMetadataChanges(currentMetadata: NotebookCellMetadata, newMetadata: any) {
		let result: { [key: string]: any } = {};
		let newLangauge: string | undefined = undefined;
		try {
			const newMetadataObj = JSON.parse(newMetadata);
			const keys = new Set([...Object.keys(newMetadataObj)]);
			for (let key of keys) {
				switch (key as keyof NotebookCellMetadata) {
					case 'breakpointMargin':
					case 'editable':
					case 'hasExecutionOrder':
					case 'inputCollapsed':
					case 'outputCollapsed':
					case 'runnable':
						// boolean
						if (typeof newMetadataObj[key] === 'boolean') {
							result[key] = newMetadataObj[key];
						} else {
							result[key] = currentMetadata[key as keyof NotebookCellMetadata];
						}
						break;

					case 'executionOrder':
					case 'lastRunDuration':
						// number
						if (typeof newMetadataObj[key] === 'number') {
							result[key] = newMetadataObj[key];
						} else {
							result[key] = currentMetadata[key as keyof NotebookCellMetadata];
						}
						break;
					case 'runState':
						// enum
						if (typeof newMetadataObj[key] === 'number' && [1, 2, 3, 4].indexOf(newMetadataObj[key]) >= 0) {
							result[key] = newMetadataObj[key];
						} else {
							result[key] = currentMetadata[key as keyof NotebookCellMetadata];
						}
						break;
					case 'statusMessage':
						// string
						if (typeof newMetadataObj[key] === 'string') {
							result[key] = newMetadataObj[key];
						} else {
							result[key] = currentMetadata[key as keyof NotebookCellMetadata];
						}
						break;
					default:
						if (key === 'language') {
							newLangauge = newMetadataObj[key];
						}
						result[key] = newMetadataObj[key];
						break;
				}
			}

			if (newLangauge !== undefined && newLangauge !== this.cell.modified!.language) {
490
				const index = this.notebookEditor.textModel!.cells.indexOf(this.cell.modified!);
R
rebornix 已提交
491
				this.notebookEditor.textModel!.applyEdits(
492 493
					this.notebookEditor.textModel!.versionId,
					[{ editType: CellEditType.CellLanguage, index, language: newLangauge }],
494 495
					true,
					undefined,
496 497
					() => undefined,
					undefined
498
				);
499
			}
500

R
rebornix 已提交
501 502 503 504 505 506
			const index = this.notebookEditor.textModel!.cells.indexOf(this.cell.modified!);

			if (index < 0) {
				return;
			}

R
rebornix 已提交
507
			this.notebookEditor.textModel!.applyEdits(this.notebookEditor.textModel!.versionId, [
R
rebornix 已提交
508
				{ editType: CellEditType.Metadata, index, metadata: result }
509
			], true, undefined, () => undefined, undefined);
510 511 512 513
		} catch {
		}
	}

514
	private _buildMetadataEditor() {
515
		if (this.cell.type === 'modified' || this.cell.type === 'unchanged') {
R
rebornix 已提交
516 517
			const originalMetadataSource = this._getFormatedMetadataJSON(this.cell.original?.metadata || {}, this.cell.original?.language);
			const modifiedMetadataSource = this._getFormatedMetadataJSON(this.cell.modified?.metadata || {}, this.cell.modified?.language);
518 519 520 521
			this._metadataEditor = this.instantiationService.createInstance(DiffEditorWidget, this._metadataEditorContainer!, {
				...fixedDiffEditorOptions,
				overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
				readOnly: false,
R
rebornix 已提交
522 523
				originalEditable: false,
				ignoreTrimWhitespace: false
524 525
			});

526
			this._metadataEditorContainer?.classList.add('diff');
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

			const mode = this.modeService.create('json');
			const originalMetadataModel = this.modelService.createModel(originalMetadataSource, mode, CellUri.generateCellMetadataUri(this.cell.original!.uri, this.cell.original!.handle), false);
			const modifiedMetadataModel = this.modelService.createModel(modifiedMetadataSource, mode, CellUri.generateCellMetadataUri(this.cell.modified!.uri, this.cell.modified!.handle), false);
			this._metadataEditor.setModel({
				original: originalMetadataModel,
				modified: modifiedMetadataModel
			});

			this._register(originalMetadataModel);
			this._register(modifiedMetadataModel);

			this._layoutInfo.metadataHeight = this._metadataEditor.getContentHeight();
			this.layout({ metadataEditor: true });

			this._register(this._metadataEditor.onDidContentSizeChange((e) => {
				if (e.contentHeightChanged && this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
					this._layoutInfo.metadataHeight = e.contentHeight;
					this.layout({ metadataEditor: true });
				}
			}));
R
rebornix 已提交
548

549
			let respondingToContentChange = false;
R
rebornix 已提交
550

551 552 553 554 555 556 557
			this._register(modifiedMetadataModel.onDidChangeContent(() => {
				respondingToContentChange = true;
				const value = modifiedMetadataModel.getValue();
				this._applySanitizedMetadataChanges(this.cell.modified!.metadata, value);
				this._metadataHeader.refresh();
				respondingToContentChange = false;
			}));
558

559 560 561 562 563 564 565 566 567 568
			this._register(this.cell.modified!.onDidChangeMetadata(() => {
				if (respondingToContentChange) {
					return;
				}

				const modifiedMetadataSource = this._getFormatedMetadataJSON(this.cell.modified?.metadata || {}, this.cell.modified?.language);
				modifiedMetadataModel.setValue(modifiedMetadataSource);
			}));

			return;
R
rebornix 已提交
569 570
		}

571 572 573
		this._metadataEditor = this.instantiationService.createInstance(CodeEditorWidget, this._metadataEditorContainer!, {
			...fixedEditorOptions,
			dimension: {
R
rebornix 已提交
574
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
575
				height: 0
576
			},
577 578
			overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
			readOnly: false
579 580
		}, {});

581
		const mode = this.modeService.create('jsonc');
R
rebornix 已提交
582
		const originalMetadataSource = this._getFormatedMetadataJSON(
R
rebornix 已提交
583 584 585
			this.cell.type === 'insert'
				? this.cell.modified!.metadata || {}
				: this.cell.original!.metadata || {});
586 587 588 589 590 591 592 593 594
		const uri = this.cell.type === 'insert'
			? this.cell.modified!.uri
			: this.cell.original!.uri;
		const handle = this.cell.type === 'insert'
			? this.cell.modified!.handle
			: this.cell.original!.handle;

		const modelUri = CellUri.generateCellMetadataUri(uri, handle);
		const metadataModel = this.modelService.createModel(originalMetadataSource, mode, modelUri, false);
595
		this._metadataEditor.setModel(metadataModel);
596
		this._register(metadataModel);
R
rebornix 已提交
597

598 599 600 601
		this._layoutInfo.metadataHeight = this._metadataEditor.getContentHeight();
		this.layout({ metadataEditor: true });

		this._register(this._metadataEditor.onDidContentSizeChange((e) => {
R
rebornix 已提交
602
			if (e.contentHeightChanged && this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
603 604 605 606
				this._layoutInfo.metadataHeight = e.contentHeight;
				this.layout({ metadataEditor: true });
			}
		}));
R
rebornix 已提交
607 608
	}

R
rebornix 已提交
609 610 611 612 613 614 615 616 617 618
	private _getFormatedOutputJSON(outputs: any[]) {
		const content = JSON.stringify(outputs);

		const edits = format(content, undefined, {});
		const source = applyEdits(content, edits);

		return source;
	}

	private _buildOutputEditor() {
619
		if ((this.cell.type === 'modified' || this.cell.type === 'unchanged') && !this.notebookEditor.textModel!.transientOptions.transientOutputs) {
R
rebornix 已提交
620 621 622 623
			const originalOutputsSource = this._getFormatedOutputJSON(this.cell.original?.outputs || []);
			const modifiedOutputsSource = this._getFormatedOutputJSON(this.cell.modified?.outputs || []);
			if (originalOutputsSource !== modifiedOutputsSource) {
				this._outputEditor = this.instantiationService.createInstance(DiffEditorWidget, this._outputEditorContainer!, {
624
					...fixedDiffEditorOptions,
R
rebornix 已提交
625
					overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
R
rebornix 已提交
626 627
					readOnly: true,
					ignoreTrimWhitespace: false
R
rebornix 已提交
628 629
				});

630
				this._outputEditorContainer?.classList.add('diff');
R
rebornix 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

				const mode = this.modeService.create('json');
				const originalModel = this.modelService.createModel(originalOutputsSource, mode, undefined, true);
				const modifiedModel = this.modelService.createModel(modifiedOutputsSource, mode, undefined, true);
				this._outputEditor.setModel({
					original: originalModel,
					modified: modifiedModel
				});

				this._layoutInfo.outputHeight = this._outputEditor.getContentHeight();
				this.layout({ outputEditor: true });

				this._register(this._outputEditor.onDidContentSizeChange((e) => {
					if (e.contentHeightChanged && this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
						this._layoutInfo.outputHeight = e.contentHeight;
						this.layout({ outputEditor: true });
					}
				}));
R
rebornix 已提交
649 650 651 652 653 654

				this._register(this.cell.modified!.onDidChangeOutputs(() => {
					const modifiedOutputsSource = this._getFormatedOutputJSON(this.cell.modified?.outputs || []);
					modifiedModel.setValue(modifiedOutputsSource);
					this._outputHeader.refresh();
				}));
R
rebornix 已提交
655 656 657

				return;
			}
R
rebornix 已提交
658
		}
R
rebornix 已提交
659 660 661 662 663 664

		this._outputEditor = this.instantiationService.createInstance(CodeEditorWidget, this._outputEditorContainer!, {
			...fixedEditorOptions,
			dimension: {
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
				height: 0
665 666
			},
			overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
R
rebornix 已提交
667 668 669 670
		}, {});

		const mode = this.modeService.create('json');
		const originaloutputSource = this._getFormatedOutputJSON(
R
rebornix 已提交
671 672 673 674 675
			this.notebookEditor.textModel!.transientOptions
				? []
				: this.cell.type === 'insert'
					? this.cell.modified!.outputs || []
					: this.cell.original!.outputs || []);
R
rebornix 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		const outputModel = this.modelService.createModel(originaloutputSource, mode, undefined, true);
		this._outputEditor.setModel(outputModel);

		this._layoutInfo.outputHeight = this._outputEditor.getContentHeight();
		this.layout({ outputEditor: true });

		this._register(this._outputEditor.onDidContentSizeChange((e) => {
			if (e.contentHeightChanged && this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
				this._layoutInfo.outputHeight = e.contentHeight;
				this.layout({ outputEditor: true });
			}
		}));
	}

	protected layoutNotebookCell() {
		this.notebookEditor.layoutNotebookCell(
			this.cell,
			this._layoutInfo.editorHeight
			+ this._layoutInfo.editorMargin
			+ this._layoutInfo.metadataHeight
			+ this._layoutInfo.metadataStatusHeight
			+ this._layoutInfo.outputHeight
			+ this._layoutInfo.outputStatusHeight
			+ this._layoutInfo.bodyMargin
		);
R
rebornix 已提交
701 702
	}

R
rebornix 已提交
703 704 705
	abstract initData(): void;
	abstract styleContainer(container: HTMLElement): void;
	abstract buildSourceEditor(sourceContainer: HTMLElement): void;
R
rebornix 已提交
706
	abstract onDidLayoutChange(event: CellDiffViewModelLayoutChangeEvent): void;
R
rebornix 已提交
707
	abstract layout(state: { outerWidth?: boolean, editorHeight?: boolean, metadataEditor?: boolean, outputEditor?: boolean }): void;
R
rebornix 已提交
708 709 710 711 712 713 714 715
}

export class DeletedCell extends AbstractCellRenderer {
	private _editor!: CodeEditorWidget;
	constructor(
		readonly notebookEditor: INotebookTextDiffEditor,
		readonly cell: CellDiffViewModel,
		readonly templateData: CellDiffRenderTemplate,
R
rebornix 已提交
716 717
		@IModeService readonly modeService: IModeService,
		@IModelService readonly modelService: IModelService,
R
rebornix 已提交
718 719
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
	) {
720
		super(notebookEditor, cell, templateData, 'left', instantiationService, modeService, modelService);
R
rebornix 已提交
721 722 723 724 725 726
	}

	initData(): void {
	}

	styleContainer(container: HTMLElement) {
727
		container.classList.add('removed');
R
rebornix 已提交
728
	}
R
rebornix 已提交
729

R
rebornix 已提交
730 731
	buildSourceEditor(sourceContainer: HTMLElement): void {
		const originalCell = this.cell.original!;
R
rebornix 已提交
732
		const lineCount = originalCell.textBuffer.getLineCount();
R
rebornix 已提交
733
		const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
R
rebornix 已提交
734
		const editorHeight = lineCount * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
R
rebornix 已提交
735 736

		const editorContainer = DOM.append(sourceContainer, DOM.$('.editor-container'));
R
rebornix 已提交
737 738 739 740

		this._editor = this.instantiationService.createInstance(CodeEditorWidget, editorContainer, {
			...fixedEditorOptions,
			dimension: {
R
rebornix 已提交
741
				width: (this.notebookEditor.getLayoutInfo().width - 2 * DIFF_CELL_MARGIN) / 2 - 18,
R
rebornix 已提交
742
				height: editorHeight
743 744
			},
			overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
R
rebornix 已提交
745
		}, {});
R
rebornix 已提交
746
		this._layoutInfo.editorHeight = editorHeight;
R
rebornix 已提交
747 748 749

		this._register(this._editor.onDidContentSizeChange((e) => {
			if (e.contentHeightChanged) {
R
rebornix 已提交
750 751
				this._layoutInfo.editorHeight = e.contentHeight;
				this.layout({ editorHeight: true });
R
rebornix 已提交
752 753 754 755 756 757 758 759
			}
		}));

		originalCell.resolveTextModelRef().then(ref => {
			this._register(ref);

			const textModel = ref.object.textEditorModel;
			this._editor.setModel(textModel);
R
rebornix 已提交
760 761
			this._layoutInfo.editorHeight = this._editor.getContentHeight();
			this.layout({ editorHeight: true });
R
rebornix 已提交
762
		});
R
rebornix 已提交
763 764 765

	}

R
rebornix 已提交
766 767
	onDidLayoutChange(e: CellDiffViewModelLayoutChangeEvent) {
		if (e.outerWidth !== undefined) {
R
rebornix 已提交
768 769 770
			this.layout({ outerWidth: true });
		}
	}
R
rebornix 已提交
771
	layout(state: { outerWidth?: boolean, editorHeight?: boolean, metadataEditor?: boolean, outputEditor?: boolean }) {
R
rebornix 已提交
772
		if (state.editorHeight || state.outerWidth) {
R
rebornix 已提交
773
			this._editor.layout({
R
rebornix 已提交
774
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
R
rebornix 已提交
775
				height: this._layoutInfo.editorHeight
R
rebornix 已提交
776 777
			});
		}
R
rebornix 已提交
778

R
rebornix 已提交
779 780
		if (state.metadataEditor || state.outerWidth) {
			this._metadataEditor?.layout({
R
rebornix 已提交
781
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
R
rebornix 已提交
782 783 784 785
				height: this._layoutInfo.metadataHeight
			});
		}

R
rebornix 已提交
786 787 788 789 790 791 792 793
		if (state.outputEditor || state.outerWidth) {
			this._outputEditor?.layout({
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
				height: this._layoutInfo.outputHeight
			});
		}

		this.layoutNotebookCell();
R
rebornix 已提交
794 795 796 797 798 799 800 801 802 803
	}
}

export class InsertCell extends AbstractCellRenderer {
	private _editor!: CodeEditorWidget;
	constructor(
		readonly notebookEditor: INotebookTextDiffEditor,
		readonly cell: CellDiffViewModel,
		readonly templateData: CellDiffRenderTemplate,
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
R
rebornix 已提交
804 805
		@IModeService readonly modeService: IModeService,
		@IModelService readonly modelService: IModelService,
R
rebornix 已提交
806
	) {
807
		super(notebookEditor, cell, templateData, 'right', instantiationService, modeService, modelService);
R
rebornix 已提交
808 809 810 811
	}

	initData(): void {
	}
R
rebornix 已提交
812

R
rebornix 已提交
813
	styleContainer(container: HTMLElement): void {
814
		container.classList.add('inserted');
R
rebornix 已提交
815 816 817 818
	}

	buildSourceEditor(sourceContainer: HTMLElement): void {
		const modifiedCell = this.cell.modified!;
R
rebornix 已提交
819
		const lineCount = modifiedCell.textBuffer.getLineCount();
R
rebornix 已提交
820
		const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
R
rebornix 已提交
821
		const editorHeight = lineCount * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
R
rebornix 已提交
822
		const editorContainer = DOM.append(sourceContainer, DOM.$('.editor-container'));
R
rebornix 已提交
823 824 825 826

		this._editor = this.instantiationService.createInstance(CodeEditorWidget, editorContainer, {
			...fixedEditorOptions,
			dimension: {
R
rebornix 已提交
827
				width: (this.notebookEditor.getLayoutInfo().width - 2 * DIFF_CELL_MARGIN) / 2 - 18,
R
rebornix 已提交
828
				height: editorHeight
829
			},
R
rebornix 已提交
830 831
			overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
			readOnly: false
R
rebornix 已提交
832 833
		}, {});

834 835
		this._layoutInfo.editorHeight = editorHeight;

R
rebornix 已提交
836 837
		this._register(this._editor.onDidContentSizeChange((e) => {
			if (e.contentHeightChanged) {
R
rebornix 已提交
838 839
				this._layoutInfo.editorHeight = e.contentHeight;
				this.layout({ editorHeight: true });
R
rebornix 已提交
840 841 842 843 844 845 846 847
			}
		}));

		modifiedCell.resolveTextModelRef().then(ref => {
			this._register(ref);

			const textModel = ref.object.textEditorModel;
			this._editor.setModel(textModel);
R
rebornix 已提交
848 849
			this._layoutInfo.editorHeight = this._editor.getContentHeight();
			this.layout({ editorHeight: true });
R
rebornix 已提交
850 851 852 853 854
		});
	}

	onDidLayoutChange(e: CellDiffViewModelLayoutChangeEvent) {
		if (e.outerWidth !== undefined) {
R
rebornix 已提交
855 856 857 858
			this.layout({ outerWidth: true });
		}
	}

R
rebornix 已提交
859
	layout(state: { outerWidth?: boolean, editorHeight?: boolean, metadataEditor?: boolean, outputEditor?: boolean }) {
R
rebornix 已提交
860
		if (state.editorHeight || state.outerWidth) {
R
rebornix 已提交
861
			this._editor.layout({
R
rebornix 已提交
862
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
R
rebornix 已提交
863
				height: this._layoutInfo.editorHeight
R
rebornix 已提交
864 865
			});
		}
R
rebornix 已提交
866

R
rebornix 已提交
867 868
		if (state.metadataEditor || state.outerWidth) {
			this._metadataEditor?.layout({
R
rebornix 已提交
869
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
R
rebornix 已提交
870 871 872 873
				height: this._layoutInfo.metadataHeight
			});
		}

R
rebornix 已提交
874 875 876 877 878 879 880 881
		if (state.outputEditor || state.outerWidth) {
			this._outputEditor?.layout({
				width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
				height: this._layoutInfo.outputHeight
			});
		}

		this.layoutNotebookCell();
R
rebornix 已提交
882 883 884 885
	}
}

export class ModifiedCell extends AbstractCellRenderer {
R
rebornix 已提交
886
	private _editor?: DiffEditorWidget;
R
rebornix 已提交
887 888 889 890 891 892
	private _editorContainer!: HTMLElement;
	constructor(
		readonly notebookEditor: INotebookTextDiffEditor,
		readonly cell: CellDiffViewModel,
		readonly templateData: CellDiffRenderTemplate,
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
R
rebornix 已提交
893 894
		@IModeService readonly modeService: IModeService,
		@IModelService readonly modelService: IModelService,
R
rebornix 已提交
895
	) {
896
		super(notebookEditor, cell, templateData, 'full', instantiationService, modeService, modelService);
R
rebornix 已提交
897
	}
R
rebornix 已提交
898

R
rebornix 已提交
899 900 901 902 903 904 905 906
	initData(): void {
	}

	styleContainer(container: HTMLElement): void {
	}

	buildSourceEditor(sourceContainer: HTMLElement): void {
		const modifiedCell = this.cell.modified!;
R
rebornix 已提交
907
		const lineCount = modifiedCell.textBuffer.getLineCount();
R
rebornix 已提交
908
		const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
R
rebornix 已提交
909
		const editorHeight = lineCount * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
R
rebornix 已提交
910
		this._editorContainer = DOM.append(sourceContainer, DOM.$('.editor-container'));
R
rebornix 已提交
911 912

		this._editor = this.instantiationService.createInstance(DiffEditorWidget, this._editorContainer, {
913
			...fixedDiffEditorOptions,
R
rebornix 已提交
914
			overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
R
rebornix 已提交
915 916
			originalEditable: false,
			ignoreTrimWhitespace: false
R
rebornix 已提交
917
		});
918
		this._editorContainer.classList.add('diff');
R
rebornix 已提交
919 920

		this._editor.layout({
R
rebornix 已提交
921
			width: this.notebookEditor.getLayoutInfo().width - 2 * DIFF_CELL_MARGIN,
R
rebornix 已提交
922 923 924 925 926 927 928
			height: editorHeight
		});

		this._editorContainer.style.height = `${editorHeight}px`;

		this._register(this._editor.onDidContentSizeChange((e) => {
			if (e.contentHeightChanged) {
R
rebornix 已提交
929 930
				this._layoutInfo.editorHeight = e.contentHeight;
				this.layout({ editorHeight: true });
R
rebornix 已提交
931 932 933
			}
		}));

R
rebornix 已提交
934
		this._initializeSourceDiffEditor();
R
rebornix 已提交
935 936
	}

R
rebornix 已提交
937
	private async _initializeSourceDiffEditor() {
R
rebornix 已提交
938 939 940 941 942 943 944 945 946 947
		const originalCell = this.cell.original!;
		const modifiedCell = this.cell.modified!;

		const originalRef = await originalCell.resolveTextModelRef();
		const modifiedRef = await modifiedCell.resolveTextModelRef();
		const textModel = originalRef.object.textEditorModel;
		const modifiedTextModel = modifiedRef.object.textEditorModel;
		this._register(originalRef);
		this._register(modifiedRef);

R
rebornix 已提交
948
		this._editor!.setModel({
R
rebornix 已提交
949 950 951 952
			original: textModel,
			modified: modifiedTextModel
		});

R
rebornix 已提交
953 954 955 956 957 958 959 960 961 962 963 964
		const contentHeight = this._editor!.getContentHeight();
		this._layoutInfo.editorHeight = contentHeight;
		this.layout({ editorHeight: true });

	}

	onDidLayoutChange(e: CellDiffViewModelLayoutChangeEvent) {
		if (e.outerWidth !== undefined) {
			this.layout({ outerWidth: true });
		}
	}

R
rebornix 已提交
965
	layout(state: { outerWidth?: boolean, editorHeight?: boolean, metadataEditor?: boolean, outputEditor?: boolean }) {
R
rebornix 已提交
966 967 968 969 970
		if (state.editorHeight || state.outerWidth) {
			this._editorContainer.style.height = `${this._layoutInfo.editorHeight}px`;
			this._editor!.layout();
		}

R
rebornix 已提交
971
		if (state.metadataEditor || state.outerWidth) {
972 973
			if (this._metadataEditorContainer) {
				this._metadataEditorContainer.style.height = `${this._layoutInfo.metadataHeight}px`;
R
rebornix 已提交
974
				this._metadataEditor?.layout();
975
			}
R
rebornix 已提交
976 977
		}

R
rebornix 已提交
978 979 980 981 982 983
		if (state.outputEditor || state.outerWidth) {
			if (this._outputEditorContainer) {
				this._outputEditorContainer.style.height = `${this._layoutInfo.outputHeight}px`;
				this._outputEditor?.layout();
			}
		}
R
rebornix 已提交
984

R
rebornix 已提交
985
		this.layoutNotebookCell();
R
rebornix 已提交
986 987
	}
}