Add document on drop sample

https://github.com/microsoft/vscode/issues/142990
This commit is contained in:
Matt Bierner
2022-04-13 15:04:35 -07:00
parent fbdb9c5bc4
commit a0a7c07db4
14 changed files with 3312 additions and 0 deletions

View File

@ -261,6 +261,7 @@ const samples = [
{ description: 'virtual-document-sample', excludeFromReadme: true, path: 'virtual-document-sample', guide: null, apis: [], contributions: [] },
{ description: 'webpack-sample', excludeFromReadme: true, path: 'webpack-sample', guide: null, apis: [], contributions: [] },
{ description: 'welcome-view-content-sample', excludeFromReadme: true, path: 'welcome-view-content-sample', guide: null, apis: [], contributions: [] },
{ description: 'drop-on-document', excludeFromReadme: true, path: 'drop-on-document', guide: null, apis: [], contributions: [] },
]
/** LSP specific samples */

View File

@ -0,0 +1,20 @@
/**@type {import('eslint').Linter.Config} */
// eslint-disable-next-line no-undef
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'semi': [2, "always"],
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/explicit-module-boundary-types': 0,
'@typescript-eslint/no-non-null-assertion': 0,
}
};

4
drop-on-document/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
out
node_modules
.vscode-test/
*.vsix

View File

@ -0,0 +1,9 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"dbaeumer.vscode-eslint"
]
}

35
drop-on-document/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,35 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "npm: watch"
},
{
"name": "Run Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test"
],
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
],
"preLaunchTask": "npm: watch"
}
]
}

View File

@ -0,0 +1,3 @@
{
"editor.insertSpaces": false
}

20
drop-on-document/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

View File

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

View File

@ -0,0 +1,9 @@
# Document on Drop Sample
This sample shows usage of the [document on drop API proposal](https://github.com/microsoft/vscode/issues/142990).
This sample adds two sample drop providers for plain text files:
- `ReverseTextOnDropProvider` This provider reverses any text dropped into a plain text editor.
- `FileNameListOnDropProvider` This provider inserts a numbered list of files names. It accepts dropped files from VS Code's explorer, VS Code's open editors view, or from the operating system.

2998
drop-on-document/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "document-on-drop-sample",
"displayName": "Document On Drop Sample",
"description": "Shows use of the document on drop API proposal",
"version": "0.0.1",
"publisher": "vscode-samples",
"private": true,
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"enabledApiProposals": [
"textEditorDrop"
],
"engines": {
"vscode": "^1.67.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onLanguage:plaintext"
],
"main": "./out/extension.js",
"contributes": {},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^12.12.0",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^4.16.0",
"@typescript-eslint/parser": "^4.16.0",
"eslint": "^7.21.0",
"typescript": "^4.5.5"
}
}

View File

@ -0,0 +1,105 @@
import * as vscode from 'vscode';
import * as path from 'path';
const uriListMime = 'text/uri-list';
/**
* Provider that reverses dropped text.
*
* Note this does not apply to text that is drag and dropped with-in the current editor,
* only for text dropped from external apps.
*/
class ReverseTextOnDropProvider implements vscode.DocumentOnDropProvider {
async provideDocumentOnDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.SnippetTextEdit | undefined> {
// Check the uri list to see if we have some kind of text data
const dataTransferItem = dataTransfer.get('text') ?? dataTransfer.get('text/plain');
if (!dataTransferItem) {
return undefined;
}
const text = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
// Adding the reversed text
snippet.appendText([...text].reverse().join(''));
return new vscode.SnippetTextEdit(new vscode.Range(position, position), snippet);
}
}
/**
* Provider that inserts a numbered list of the names of dropped files.
*
* Try dropping one or more files from:
*
* - VS Code's explorer
* - The operating system
* - The open editors view
*/
class FileNameListOnDropProvider implements vscode.DocumentOnDropProvider {
async provideDocumentOnDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.SnippetTextEdit | undefined> {
// Check the data transfer to see if we have dropped a list of uris
const dataTransferItem = dataTransfer.get(uriListMime);
if (!dataTransferItem) {
return undefined;
}
// 'text/uri-list' contains a list of uris separated by new lines.
// Parse this to an array of uris.
const urlList = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
const uris: vscode.Uri[] = [];
for (const resource of urlList.split('\n')) {
try {
uris.push(vscode.Uri.parse(resource));
} catch {
// noop
}
}
if (!uris.length) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
uris.forEach((uri, index) => {
const name = path.basename(uri.path);
snippet.appendText(`${index + 1}. ${name}`);
snippet.appendTabstop();
if (index <= uris.length - 1 && uris.length > 1) {
snippet.appendText('\n');
}
});
return new vscode.SnippetTextEdit(new vscode.Range(position, position), snippet);
}
}
export function activate(context: vscode.ExtensionContext) {
// Enable our providers in plaintext files
const selector: vscode.DocumentSelector = { language: 'plaintext' };
// Register our providers
context.subscriptions.push(vscode.languages.registerDocumentOnDropProvider(selector, new ReverseTextOnDropProvider()));
context.subscriptions.push(vscode.languages.registerDocumentOnDropProvider(selector, new FileNameListOnDropProvider()));
}

View File

@ -0,0 +1,47 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/142990
export class SnippetTextEdit {
snippet: SnippetString;
range: Range;
constructor(range: Range, snippet: SnippetString);
}
/**
* Provider which handles dropping of resources into a text editor.
*
* The user can drop into a text editor by holding down `shift` while dragging. Requires `workbench.editor.dropIntoEditor.enabled` to be on.
*/
export interface DocumentOnDropProvider {
/**
* Provide edits which inserts the content being dragged and dropped into the document.
*
* @param document The document in which the drop occurred.
* @param position The position in the document where the drop occurred.
* @param dataTransfer A {@link DataTransfer} object that holds data about what is being dragged and dropped.
* @param token A cancellation token.
*
* @return A {@link SnippetTextEdit} or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideDocumentOnDropEdits(document: TextDocument, position: Position, dataTransfer: DataTransfer, token: CancellationToken): ProviderResult<SnippetTextEdit>;
}
export namespace languages {
/**
* Registers a new {@link DocumentOnDropProvider}.
*
* @param selector A selector that defines the documents this provider applies to.
* @param provider A drop provider.
*
* @return A {@link Disposable} that unregisters this provider when disposed of.
*/
export function registerDocumentOnDropProvider(selector: DocumentSelector, provider: DocumentOnDropProvider): Disposable;
}
}

View File

@ -0,0 +1,12 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"lib": ["es2020"],
"outDir": "out",
"sourceMap": true,
"rootDir": "src",
"strict": true
},
"exclude": ["node_modules", ".vscode-test"]
}