All files / services/notebook notebook-serializer.ts

100% Statements 16/16
100% Branches 0/0
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      10x       10x 10x           7x       7x 7x   2x     7x 8x           8x   8x     7x       4x   4x 6x               4x    
import * as vscode from 'vscode';
import { container } from 'tsyringe';
import { ServiceToken } from '@src/services/tokens';
import { NOTEBOOK_TYPE } from './notebook-controller';
 
interface NotebookData {
	cells: NotebookCell[]
}
 
interface NotebookCell {
	language: string;
	value: string;
	kind: vscode.NotebookCellKind;
	editable?: boolean;
	metadata?: Record<string, any>;
}
 
export class NotebookSerializer implements vscode.NotebookSerializer {
 
	public readonly label: string = 'Mentor Notebook Serializer';
 
	constructor() {
		// Self-register with the extension context for automatic disposal
		const context = container.resolve<vscode.ExtensionContext>(ServiceToken.ExtensionContext);
		context.subscriptions.push(
			vscode.workspace.registerNotebookSerializer(NOTEBOOK_TYPE, this, { transientOutputs: true })
		);
	}
 
	public async deserializeNotebook(data: Uint8Array, _token: vscode.CancellationToken): Promise<vscode.NotebookData> {
		const contents = new TextDecoder().decode(data);
 
		let raw: NotebookData;
 
		try {
			raw = JSON.parse(contents);
		} catch {
			raw = { cells: [] };
		}
 
		const cells = raw.cells.map(item => {
			const cell = new vscode.NotebookCellData(
				item.kind,
				item.value,
				item.language,
			);
 
			cell.metadata = item.metadata;
 
			return cell;
		});
 
		return new vscode.NotebookData(cells);
	}
 
	public async serializeNotebook(data: vscode.NotebookData, _token: vscode.CancellationToken): Promise<Uint8Array> {
		const contents: NotebookData = { cells: [] };
 
		for (const cell of data.cells) {
			contents.cells.push({
				kind: cell.kind,
				language: cell.languageId,
				metadata: cell.metadata,
				value: cell.value
			});
		}
 
		return new TextEncoder().encode(JSON.stringify(contents));
	}
}