Added Text Document provider example

This commit is contained in:
Erich Gamma
2016-02-09 23:19:35 +01:00
parent ac622d9f4a
commit 64334866f0
15 changed files with 309 additions and 0 deletions

View File

@ -0,0 +1,2 @@
out
node_modules

View File

@ -0,0 +1,28 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/src",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}

View File

@ -0,0 +1,10 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}

View File

@ -0,0 +1,30 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",
// we want to run npm
"command": "npm",
// the command is a shell script
"isShellCommand": true,
// show the output window only if unrecognized errors occur.
"showOutput": "silent",
// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],
// The tsc compiler is started in watching mode
"isWatching": true,
// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}

View File

@ -0,0 +1,9 @@
.vscode/**
typings/**
out/test/**
test/**
src/**
**/*.map
.gitignore
tsconfig.json
vsc-extension-quickstart.md

View File

@ -0,0 +1,22 @@
# CSS Properties Preview Sample
This is an sample extension that illustrates the use of virtual documents or `TextDocumentContentProviders` together with the `vscode.previewHtml`
[command](https://code.visualstudio.com/docs/extensionAPI/vscode-api-commands#_commands).
It is not intended as a product quality extension.
The purpose of the extension is to show a preview of the properties in the declaration block of a CSS rule. To play with the extension:
- Open a CSS file
- Use `Show CSS Properties Preview`
- Position the cursor inside the declaration block of the rule
- The properties are rendered in the preview
- Edit the propertis and the preview is updated
![Navigation](images/preview.gif)
# How it works
- The extension implements and registers a `TextDocumentProvider` for a particular resource URI.
- The TextDocumentProvider creates a HTML document that contains the declaration block of the selected CSS Rule in the active editor.
- The generated HTML document is then opened in an editor in the 2nd Column using the command `vscode.previewHtml`.

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

@ -0,0 +1,47 @@
{
"name": "vscode-css-properties",
"displayName": "Preview CSS Propertis Sample",
"description": "A sample illustrating the of TextContentProviders and the `vscode.previewHtml` command. Introduce in verson 0.10.7.",
"version": "0.0.4",
"publisher": "eg2",
"galleryBanner": {
"color": "#5c2d91",
"theme": "dark"
},
"bugs": {
"url": "https://github.com/Microsoft/vscode-extension-samples/issues",
"email": "egamma@microsoft.com"
},
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/vscode-extension-samples.git"
},
"categories": [
"Other"
],
"engines": {
"vscode": "^0.10.7"
},
"activationEvents": [
"onCommand:extension.showCssPropertyPreview"
],
"main": "./out/src/extension",
"contributes": {
"commands": [
{
"command": "extension.showCssPropertyPreview",
"title": "Show CSS Properties Preview"
}
]
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install",
"tslint": "tslint -c tslint.json src/extension.ts"
},
"devDependencies": {
"typescript": "^1.7.5",
"vscode": "^0.11.0"
}
}

View File

@ -0,0 +1,96 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let previewUri = vscode.Uri.parse('css-preview://authority/css-preview');
class TextDocumentContentProvider implements vscode.TextDocumentContentProvider {
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
public provideTextDocumentContent(uri: vscode.Uri): string {
return this.createCssSnippet();
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this._onDidChange.event;
}
public update(uri: vscode.Uri) {
this._onDidChange.fire(uri);
}
private createCssSnippet() {
let editor = vscode.window.activeTextEditor;
if (!(editor.document.languageId === 'css')) {
return this.errorSnippet("Active editor doesn't show a CSS document - no properties to preview.")
}
return this.extractSnippet();
}
private extractSnippet(): string {
let editor = vscode.window.activeTextEditor;
let text = editor.document.getText();
let selStart = editor.document.offsetAt(editor.selection.anchor);
let propStart = text.lastIndexOf('{', selStart);
let propEnd = text.indexOf('}', selStart);
if (propStart === -1 || propEnd === -1) {
return this.errorSnippet("Cannot determine the rule's properties.");
}
let properties = text.slice(propStart + 1, propEnd);
return this.snippet(properties);
}
private errorSnippet(error: string): string {
return `
<body>
${error}
</body>`;
}
private snippet(properties): string {
return `<style>
#el {
${properties}
}
</style>
<body>
<div>Preview of the CSS properties</dev>
<hr>
<div id="el">Lorem ipsum dolor sit amet, mi et mauris nec ac luctus lorem, proin leo nulla integer metus vestibulum lobortis, eget</div>
</body>`;
}
}
let provider = new TextDocumentContentProvider();
let registration = vscode.workspace.registerTextDocumentContentProvider('css-preview', provider);
vscode.workspace.onDidChangeTextDocument((e: vscode.TextDocumentChangeEvent) => {
if (e.document === vscode.window.activeTextEditor.document) {
provider.update(previewUri);
}
});
vscode.window.onDidChangeTextEditorSelection((e: vscode.TextEditorSelectionChangeEvent) => {
if (e.textEditor === vscode.window.activeTextEditor) {
provider.update(previewUri);
}
})
let disposable = vscode.commands.registerCommand('extension.showCssPropertyPreview', () => {
return vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.Two).then((success) => {
}, (reason) => {
vscode.window.showErrorMessage(reason);
});
});
context.subscriptions.push(disposable, registration);
}
export function deactivate() {
}

View File

@ -0,0 +1,22 @@
//
// Note: This example test is leveraging the Mocha test framework.
// Please refer to their documentation on https://mochajs.org/ for help.
//
// The module 'assert' provides assertion methods from node
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
import * as myExtension from '../src/extension';
// Defines a Mocha test suite to group tests of similar kind together
suite("Extension Tests", () => {
// Defines a Mocha unit test
test("Something 1", () => {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});

View File

@ -0,0 +1,22 @@
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;

View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"outDir": "out",
"noLib": true,
"sourceMap": true,
"rootDir": "."
},
"exclude": [
"node_modules"
]
}

View File

@ -0,0 +1,6 @@
{
"rules": {
"no-unused-variable": true,
"no-unused-expression": true
}
}

View File

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/node.d.ts" />

View File

@ -0,0 +1 @@
/// <reference path="../node_modules/vscode/typings/index.d.ts" />